public class MyFtpClass
{
private readonly string _destIp;
private readonly string _userName;
private readonly string _password;
public MyFtpClass(string desIp, string userName, string passowrd)
{
this._destIp = desIp;
this._userName = userName;
this._password = passowrd;
}
private FtpWebRequest OpenRequest(Uri uri,string ftpMethod)
{
FtpWebRequest request = WebRequest.Create(uri) as FtpWebRequest;
if (request != null)
{
request.Credentials = new NetworkCredential(_userName, _password);
request.UseBinary = true;
request.Method = ftpMethod;
return request;
}
else
{
return null;
}
}
private FtpWebResponse OpenResponse(Uri uri, string ftpMethod)
{
FtpWebRequest request= this.OpenRequest(uri, ftpMethod);
if (request != null)
{
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
return response;
}
else
{
return null;
}
}
/// <summary>
/// 要上传的本地文件路径
/// </summary>
/// <param name="uploadFilePath">形如:D:\\folder1\\2.jpg </param>
/// <param name="desName">形如:123.jpg 或 subFolder1/123.jpg</param>
/// <returns></returns>
public bool Upload(string uploadFilePath, string desName)
{
Stream requestStream = null;
FtpWebResponse response = null;
try
{
Uri uri = new Uri(string.Format("ftp://{0}/{1}", _destIp, desName));
FtpWebRequest request = OpenRequest(uri, WebRequestMethods.Ftp.UploadFile);
requestStream = request.GetRequestStream();
FileStream fs = File.Open(uploadFilePath, FileMode.Open);
byte[] buff = new byte[1024];
int buffRead = 0;
while (true)
{
int n = fs.Read(buff, buffRead, buff.Length);
if (n == 0)
{
break;
}
//把文件流写入请求流
requestStream.Write(buff, 0, n);
}
response = (FtpWebResponse)request.GetResponse();
return true;
}
catch (Exception)
{
throw new Exception("上传文件失败!");
}
finally
{
requestStream.Close();
response.Close();
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="serverFileName">要下载的文件名。形如:123.jpg 或 subFolder1/123.jpg</param>
/// <param name="localPath">下载至本地的路径。形如: D:\\a\\b\\</param>
/// <param name="localName">保存在本地的名称。形如:3.jpg</param>
/// <returns></returns>
public bool Download(string serverFileName, string localPath, string localName)
{
Stream responseStream=null;
FileStream fileStream=null;
try
{
Uri uri = new Uri(string.Format("ftp://{0}/{1}", _destIp, serverFileName));
FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.DownloadFile);
responseStream = downloadResponse.GetResponseStream();
fileStream = File.Create(localPath + localName);
byte[] buffer = new byte[1024];
while (true)
{
var bytesRead = responseStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
//把响应流写入文件
fileStream.Write(buffer, 0, bytesRead);
}
return true;
}
catch
{
throw new Exception("获取下载文件失败!");
}
finally
{
fileStream.Close();
responseStream.Close();
}
}
}
需要注意的流文件的读出和写入问题:
例如,
int n = fs.Read(buff, buffRead, buff.Length);
bufferRead和buff.Length指的是数组buff的索引以及长度。
流文件fs会自动维护一个指针Position,每当read n个字节时,会自动向后移动n个字节。
fileStream.Write(buffer, 0, bytesRead);是同样的道理。