参考文档:http://cache.baiducontent.com/c?m=s0cZ8DUsvIKSqpZ31zPM70S7XphWku2wLcqUqpjxkCb8MktcgKRalco_bAWz93SJ8GLBjmKOwzBZs6GIcR8qQyympXkQdtRz5z3LIYXzelbB5Lut8fdbGOHXtSQSvoyz_8_RM6lOhc0ee6sfAsARvf8CBGBcInReUJm0hPvb2Fm&p=9f3be75485cc43ea10bd9b7b16&newp=91759a40c09410eb0be296685153d8224216ed643ad0c44324b9d71fd325001c1b69e7b026221207d1c57f6101ab4d59eef73678341766dada9fca458ae7c43e78d963&s=cfcd208495d565ef&user=baidu&fm=sc&query=FTP%C9%CF%B4%AB%B4%FA%C2%EBc%23&qid=e78ebd9f00006d3f&p1=1
string ftpHOST;
string ftpUSER;
string ftpPASSWORD;
string ftpPORT;
string ftpPATH;
string url;
FileStream fs = null;
Stream ftpstream = null;
FtpWebResponse uploadResponse = null;
try
{
ftpHOST = System.Configuration.ConfigurationManager.AppSettings["FTP_HOST"];
ftpPORT = System.Configuration.ConfigurationManager.AppSettings["FTP_PORT"];
ftpUSER = System.Configuration.ConfigurationManager.AppSettings["FTP_USER"];
ftpPASSWORD = System.Configuration.ConfigurationManager.AppSettings["FTP_PASSWORD"];
ftpPATH = System.Configuration.ConfigurationManager.AppSettings["FTP_PATH"];
url = "ftp://" + ftpHOST + ":" + ftpPORT + "/" + ftpPATH + "/" + Path.GetFileName(filename);
FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
ftpReq.Credentials = new NetworkCredential(ftpUSER, ftpPASSWORD);
ftpReq.KeepAlive = false;//指定在请求完成之后是否关闭到 FTP 服务器的控制连接。
ftpReq.UseBinary = true;//指定文件传输的数据类型。
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
#region buffer长度是文件长度
fs = File.OpenRead(System.Configuration.ConfigurationManager.AppSettings["csvPATH"] + filename);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
ftpstream = ftpReq.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
#endregion
#region buffer长度是2048,已注释
//fs = File.OpenRead(System.Configuration.ConfigurationManager.AppSettings["csvPATH"] + filename);
//ftpstream = ftpReq.GetRequestStream();
//byte[] buffer = new byte[2048];
//int bytesRead = fs.Read(buffer, 0, buffer.Length);
//while (bytesRead > 0)
//{
// ftpstream.Write(buffer, 0, buffer.Length);
// bytesRead = fs.Read(buffer, 0, buffer.Length);
//}
//ftpstream.Close();
//fs.Close();
#endregion
uploadResponse = (FtpWebResponse)ftpReq.GetResponse();
/*
* FtpStatusCode指定为文件传输协议 (FTP) 操作返回的状态代码
* https://docs.microsoft.com/zh-cn/dotnet/api/system.net.ftpstatuscode?view=net-5.0
* ClosingData 指示服务器正在关闭数据连接,并且请求的文件操作成功
*/
if (uploadResponse.StatusCode == FtpStatusCode.ClosingData)
{
//上传成功
Console.WriteLine(uploadResponse.StatusCode.ToString());
}
else
{
throw new Exception(uploadResponse.StatusCode.ToString());
}
}
catch (Exception ex)
{
//上传失败
if (fs != null)
{ fs.Close(); }
if (ftpstream != null)
{ ftpstream.Close(); }
throw ex;
}
finally
{
if (uploadResponse != null)
{
uploadResponse.Close();
}
}