(4)FTP服务器下载文件

上一篇中,我们提到了怎么从FTP服务器下载文件。现在来具体讲述一下。

首先是路径配置。。

所以此处我们需要一个app.config来设置路径。

<?xml version="1.0" encoding="utf-8" ?>
<configuration> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="OnlineBankRequestFolder" value ="ftp://Online/Request/" />
<add key="OnlineBankResponseFolder" value ="ftp://Online/Response/" />
<add key ="ftpUser" value ="fsscftp"/>
<add key ="ftpPassword" value ="fssc123"/>
</appSettings>
</configuration>

另外在c#中需要获取路径

public string ftpUser = ConfigurationManager.AppSettings["ftpUser"];
public string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
public string downfolder = ConfigurationManager.AppSettings["OnlineBankRequestFolder"] + "/Request.txt";
public string savefolder = ConfigurationManager.AppSettings["OnlineBankResponseFolder"]+"/Response.xml";

然后还需要建立一个ftp请求。这时就需要建立一个ftpclient的类

  public class FtpClient
{
private string userName;
private string passWord;
private byte[] buffer = new byte[ * ]; public FtpClient(string userName, string passWord)
{
this.userName = userName;
this.passWord = passWord;
} /**/
/// <summary>
/// 创建ftp请求信息
/// </summary>
/// <param name="url">目标url地址</param>
/// <param name="useBinary">是否使用二进制传输</param>
private FtpWebRequest GetRequest(string url, bool useBinary)
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(url);
ftpRequest.Credentials = new NetworkCredential(userName, passWord);
ftpRequest.UseBinary = useBinary;
ftpRequest.KeepAlive = true;
return ftpRequest;
}
//下载文件
public void DownloadFile(string localFile, string remoteFile, bool useBinary)
{ FtpWebRequest request = GetRequest(remoteFile, useBinary);
request.Method = WebRequestMethods.Ftp.DownloadFile;
try
{
WriteStream(request.GetResponse().GetResponseStream(),File.Create(localFile));
}
catch (Exception ex)
{
throw (ex);
}
}
//将orgStream中的内容拷贝到desStream中
private void WriteStream(Stream orgStream, Stream desStream)
{
int num;
while ((num = orgStream.Read(buffer, , buffer.Length)) > )
{
desStream.Write(buffer, , num);
}
orgStream.Close();
desStream.Close();
}
}

这个类在下载时就会用到。另外还会用到一个方法,是得到保存路径。

  public string GetDataFileSavePath()
{
//FTP待导入数据文件存放的路径
string directory = savefolder;
//if (!(Directory.Exists(directory)))
// Directory.CreateDirectory(directory);
string fileName = "Cache_file.txt";
//保存路径
string savePath = System.IO.Path.Combine(directory, fileName);
//if (!File.Exists(savePath))
// File.Create(savePath);
return savePath;
}

好了。准备工作完成了。现在就可以下载了。

private void FTPDown(string txtpath,string strErrMsg="",string encodingCode = "GB2312", string strSplit = "|")
{
  string savePath = downfolder;
  if(txtpath.IndexOf("ftp")>=){
  //创建ftp请求信息
  var ftpRequest = new FtpClient(ftpUser, ftpPassword);
  savePath = GetDataFileSavePath();
  ftpRequest.DownloadFile(savePath, txtpath, true);
  }
}

这样FTP的文件就下载到本地的一个路径下面了。

上一篇:从Linux服务器下载文件到本地命令


下一篇:Linux系统 Cetos 7 中重置root密码