在ftp站点下载文件:登录连接→下载 引用:using System.Net;
using System.Net;
/// <summary>
/// ftp站点文件下载
/// </summary>
/// <param name="serverPath"></param>
/// <param name="localPath"></param>
public static void FileDownload(string serverPath, string localPath)
{
if (!Directory.Exists(fileDerectory))
{
// 如果不存在,则创建路径
Directory.CreateDirectory(fileDerectory);
}
string user = ConfigurationManager.AppSettings["User"].ToString();
string password = ConfigurationManager.AppSettings["PassWord"].ToString();
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(user, password); // 替换为你的FTP登录信息
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream ftpStream = response.GetResponseStream())
using (FileStream localFileStream = new FileStream(localPath, FileMode.Create))
{
byte[] buffer = new byte[4096]; // 你可以根据需要调整缓冲区大小
int bytesRead;
while ((bytesRead = ftpStream.Read(buffer, 0, buffer.Length)) != 0)
{
localFileStream.Write(buffer, 0, bytesRead);
}
} // 在这里,ftpStream, localFileStream, 和 response 会被自动关闭,因为我们使用了 using 语句。
TXTFileLogger.WriteLog(serverPath + "下载成功!");
}
catch (Exception ex)
{
TXTFileLogger.WriteLog(ex.Message);
// 处理异常,例如显示错误消息或记录日志等。
}
}
调用示例:
首先,确保FTP服务器上的文件存在,这里事先搭建好一个FTP站点并新建一个TXT文件
调用代码:
string serverPath = "ftp://192.168.100.48/1.txt";
string loaclPath = "1.txt";
FileDownload(serverPath, loaclPath);
MessageBox.Show(File.ReadAllText(loaclPath));
执行结果: