c#.net从ftp下载文件到本地
c#.net从ftp下载文件到本地
string TempFolderPath = System.Configuration.ConfigurationManager.AppSettings["TempFolderPath"].ToString();
string FtpUserName = System.Configuration.ConfigurationManager.AppSettings["FtpUserName"].ToString();
string FtpPassWord = System.Configuration.ConfigurationManager.AppSettings["FtpPassWord"].ToString();
string LocalFileExistsOperation = System.Configuration.ConfigurationManager.AppSettings["LocalFileExistsOperation"].ToString();
Uri uri = new Uri(FtpPath);
string FileName = Path.GetFullPath(TempFolderPath) + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(uri.LocalPath);
//创建一个文件流
FileStream fs = null;
Stream responseStream = null;
try
{
//创建一个与FTP服务器联系的FtpWebRequest对象
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
//设置请求的方法是FTP文件下载
request.Method = WebRequestMethods.Ftp.DownloadFile;
//连接登录FTP服务器
request.Credentials = new NetworkCredential(FtpUserName, FtpPassWord);
//获取一个请求响应对象
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//获取请求的响应流
responseStream = response.GetResponseStream();
//判断本地文件是否存在,如果存在,则打开和重写本地文件
if (File.Exists(FileName))
{
if (LocalFileExistsOperation == "write")
{
fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);
}
}
//判断本地文件是否存在,如果不存在,则创建本地文件
else
{
fs = File.Create(FileName);
}
if (fs != null)
{
int buffer_count = 65536;
byte[] buffer = new byte[buffer_count];
int size = 0;
while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
{
fs.Write(buffer, 0, size);
}
fs.Flush();
fs.Close();
responseStream.Close();
}
}
finally
{
if (fs != null)
fs.Close();
if (responseStream != null)
responseStream.Close();
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。