基于 Web 的 FTP 客户端






1.80/5 (2投票s)
一个用于访问 FTP 的 Web 应用程序。
引言
Microsoft .NET 框架提供了一个强大的库来访问 FTP 站点及其内容。 在本文中,我们将讨论如何从 Web 应用程序中访问它们,并从 FTP 流式传输文件并将其转储到您想要的位置。
使用代码
代码分为两部分
- FTP 助手 - 包含 FTP 方法文件的项目。
- FTP Web - 用于 FTP 的 Web 应用程序。
由于我在 ViewState 中使用它,因此必须序列化 FTPConnection
类。
[Serializable]
public class FTPConnection
以下是用于连接到 FTP 站点的方法
public FtpWebRequest ConnectToFtp(string Method)
{
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(_url));
ftpRequest.UseBinary = true;
ftpRequest.Credentials = new NetworkCredential(_username, _password);
ftpRequest.Method = Method;
ftpRequest.Proxy = null;
ftpRequest.KeepAlive = false;
ftpRequest.UsePassive = false;
return ftpRequest;
}
现在我们可以获取文件列表,包括名称和完全限定路径,来自特定 URL
/// <summary>
/// Get all files in ftp folder
/// </summary>
/// <param name="FolderUrl"></param>
/// <returns></returns>
public Dictionary<string, string> GetFileList(string FolderUrl)
{
StringBuilder filesstring = new StringBuilder();
WebResponse webResponse = null;
StreamReader sreader = null;
/// I use string type Dictionary to get both filename and filename with path
Dictionary<string, string> Files = new Dictionary<string, string>();
try
{
//you can change url to connect to ftp according to your need
FtpWebRequest ftpRequest = ConnectToFtp(FolderUrl,
WebRequestMethods.Ftp.ListDirectory);
webResponse = ftpRequest.GetResponse();
sreader = new StreamReader(webResponse.GetResponseStream());
string strline = sreader.ReadLine();
while (strline != null)
{
//Add filename and filename with path to dictionary
Files.Add(strline, FolderUrl +"/"+ strline);
}
return Files;
}
catch (Exception ex)
{
//do any thing with exception
return null;
}
finally
{
if (sreader != null)
{
sreader.Close();
}
if (webResponse != null)
{
webResponse.Close();
}
}
}
以下是如何获取可下载文件的字节
public byte[] DownloadFileFromFtp(string fileUrl)
{
StringBuilder filesstring = new StringBuilder();
WebResponse webResponse = null;
try
{
FtpWebRequest ftpRequest = ConnectToFtp(fileUrl,
WebRequestMethods.Ftp.DownloadFile);
ftpRequest.UseBinary = true;
webResponse = ftpRequest.GetResponse();
FtpWebResponse response = (FtpWebResponse)webResponse;
Stream dfileResponseStream = response.GetResponseStream();
int Length = 1024;
Byte[] buffer = new Byte[Length];
// collect all bytes of file
List<byte> filebytes = new List<byte>();
int bytesRead = dfileResponseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
for(int i= 0;i<bytesRead;i++)
// read file byte in buffer and add it to list
filebytes.Add(buffer[i]);
bytesRead = dfileResponseStream.Read(buffer, 0, Length);
}
response.Close();
return filebytes.ToArray(); // return complete byte array
}
catch (Exception ex)
{
//do any thing with exception
return null;
}
finally
{
if (webResponse != null)
{
webResponse.Close();
}
}
}
我们完成了基本的 FTP 方法。 现在我们将查看 Web 应用程序部分。
我将 FTPHelper.FTPConnection
对象存储在 ViewState 中,因为我想在页面上多次使用相同的实例。
public FTPHelper.FTPConnection FTP
{
set
{
ViewState["FTP"] = value;
}
get
{
return ViewState["FTP"] == null ? null :
(FTPHelper.FTPConnection)ViewState["FTP"];
}
}
使用下面的界面设置 FTP 站点的 FTP URL、用户名和密码
现在连接到 FTP 站点并检索根目录和文件
public void ConnectToFtp()
{
try
{
FTP = new FTPHelper.FTPConnection(txtFTPUrl.Text.ToLower().Replace(
"ftp://",""), txtUser.Text, txtPassword.Text);
Dictionary<string, string> Files = FTP.GetFileList(FTP._url);
lblWelcome.Text = "<strong> Welcome </strong> " + txtUser.Text;
tbLogin.Visible = false;
foreach (string ky in Files.Keys)
{
TreeNode trParent = new TreeNode();
trParent.Text = (string)ky; // file name
trParent.Value = Files[ky]; // fully qualified name
trVFiles.Nodes.Add(trParent);
}
}
catch(Exception ex)
{
tbLogin.Visible = false;
lblWelcome.Text = ex.Message;
lblWelcome.ForeColor = System.Drawing.Color.Red;
}
}
捕获 TreeView
控件的 SelectedNodeChanged
事件,以获取所选目录节点中的目录和文件
protected void trVFiles_SelectedNodeChanged(object sender, EventArgs e)
{
Dictionary<string,string> _filesInFolder = FTP.GetFileList(trVFiles.SelectedValue);
Dictionary<string, string> _onlyfiles = new Dictionary<string, string>();
foreach (string key in _filesInFolder.Keys)
{
// checking if file is directory
if (key.IndexOf('.') == -1)
{
TreeNode trParent = new TreeNode();
trParent.Text = (string)key;
trParent.Value = _filesInFolder[key];
// appending directory to selected parent directory
trVFiles.SelectedNode.ChildNodes.Add(trParent);
}
else
{
_onlyfiles.Add(key, _filesInFolder[key]); // seperate the files
}
}
trVFiles.SelectedNode.Expand(); //expand the selected node
BindGrid(_onlyfiles); // bind the grid with files separated
}
最后,获取 RowCommand
事件以下载所需的文件
protected void grdDetailView_RowCommand(object sender, GridViewCommandEventArgs e)
{
//CommandArgument contain the fully qualified name of the file
byte[] _downFile = FTP.DownloadFileFromFtp(e.CommandArgument.ToString());
string _fname =e.CommandArgument.ToString();
Response.ContentType = "application/"+_fname.Split('.')[1];
Response.AddHeader("Content-disposition",
"attachment; filename=" + _fname);
// stream the file byte on ftp
Response.OutputStream.Write(_downFile, 0, _downFile.Length);
Response.End();
}
就是这样。