C# 相关 FTP(File Transfer Protocol) 操作
1.获取文件目录
UsePassive:需要设置为false。 使用被动模式,因为客户端防火墙的存在,所以为了确保数据可以正常传输,所有采用被动模式。
UseBinary:指示文件的传输类型,true 指示二进制数据,false指示数据为为本,默认为true。
/// <summary>
/// 根据ftp路径返回目录下的文件名称
/// </summary>
public string[] GetFilesDetailList(string path)
{
List<string> listFileNames = new List<string>();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
ftp.UsePassive = false;
//ftp.UseBinary = true;
ftp.Credentials = new NetworkCredential("Skills", "Skills"); //用户名密码
ftp.Method = WebRequestMethods.Ftp.ListDirectory; //只带文件名
var stream = ftp.GetResponse().GetResponseStream();
StreamReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
listFileNames.Add(line);
}
reader.Close();
return listFileNames.ToArray();
}
2.下载文件
/// <summary>
/// 下载文件
/// </summary>
public void DownloadFile(string filePath)
{
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(filePath));
ftp.UsePassive = false;
ftp.UseBinary = true;
ftp.Credentials = new NetworkCredential("Skills", "Skills"); //用户名密码
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
Stream stream = ftp.GetResponse().GetResponseStream();
//Save file
string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int readCount = stream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
fs.Write(buffer, 0, readCount);
readCount = stream.Read(buffer, 0, bufferSize);
}
fs.Close();
stream.Close();
}
3.获取文件大小
/// <summary>
/// 获取指定文件大小
/// </summary>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; //获取文件大小
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("Skills", "Skills");
return reqFTP.GetResponse().ContentLength;
}