c# FTP 上传文件代码
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
//关键代码
using System.Net.WebRequestMethods.Ftp;
NetworkCredential nCredl=new NetworkCredential(FtpUser,FtpPwd);
private bool UpFile(string filename)
{
bool status = false;
FtpWebRequest ftpQ = (FtpWebRequest)WebRequest.Create(ss.FtpUrl);
ftpQ.KeepAlive = false;
FtpWebResponse response=null;
ftpQ.Credentials = nCredl;
ftpQ.Method = WebRequestMethods.Ftp.AppendFile;
FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read,FileShare.Read);
byte[] bits = null;
if (IsLimitSpeed)
{
bits = new byte[speed];
}
else
{
bits = new byte[102400];
}
int rlen = 0;
decimal filelen=(decimal)fs.Length;
long rdcount = 0;
int v=0;
long sd = getFileSize();
Stream requestStream = null;
if (sd == -1) sd = 0;
fs.Position = sd;
rdcount += sd;
try
{
requestStream = ftpQ.GetRequestStream();
while (0 != (rlen = fs.Read(bits, 0, bits.Length)))
{
requestStream.Write(bits, 0, rlen);
requestStream.Flush();
rdcount += rlen;
if (Ev_UpFleSub != null)
{
v = (int)(((decimal)rdcount / filelen) * 100);
Ev_UpFleSub(v, rdcount, this.ss, this.pb);
}
if (IsLimitSpeed)
{
System.Threading.Thread.Sleep(500);
}
}
if (requestStream != null)
{
requestStream.Close();
}
fs.Close();
}
catch (Exception ex)
{
if (fs != null)
{
fs.Dispose();
}
try
{
if (requestStream != null)
{
GC.ReRegisterForFinalize(requestStream);
}
}catch{}
throw ex;
}
return status;
}