c#Ftp上传文件

public string UploadFile(string filePath, string fileName, string ftpServerIP, string ftpUserName, string ftpPassword)
{
string file = filePath + fileName;
FileInfo fileInf = new FileInfo(file);

string uri = "ftp://" + ftpServerIP + @"/" + fileInf.Name;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFtp.Credentials = new NetworkCredential(ftpUserName, ftpPassword);

reqFtp.Method = WebRequestMethods.Ftp.UploadFile;

reqFtp.UsePassive = false;
reqFtp.UseBinary = true;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen = 0;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFtp.GetRequestStream();

contentLen = fs.Read(buff, 0, buffLength);

while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);

contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
fs.Close();
return ex.StackTrace;
}
return "文件上传成功";
}

posted @ 2017-01-23 13:16  成小伟  阅读(3763)  评论(0编辑  收藏  举报