【发布时间】:2017-11-15 02:40:28
【问题描述】:
在执行以下代码时出现以下错误
(底层连接已关闭服务器提交了一个协议 违规)
。请帮助解决这个问题。我几乎把所有关于错误的文章都扔了,但仍然没有得到解决方案。
提前致谢。
private static void Upload()
{
string sourceFile = System.IO.Path.Combine(filepath, filename);
string ftpServerIP = "Hostname";
string ftpUserID = "UserName";
string ftpPassword = "Password";
FileInfo fileInf = new FileInfo(sourceFile);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
//try
//{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Until Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
//}
//catch (Exception ex)
//{
// Console.Write(ex.Message, "Upload Error");
//}
}
【问题讨论】:
-
告诉我们log file of
FtpWebRequest;以及任何 FTP 客户端(例如 WinSCP)的相应详细日志文件,显示同一文件的上传。 -
我首先要确保您可以进行 ftp。 1) 使用 cmd.exe 并键入 > FTP。测试是否可以上传 2) 在 Windows Explorer 中输入 ftp:\\172.x.x.x\。然后浏览项目。这将验证您是否拥有凭据并且服务器是否允许 ftp 连接。
标签: c# file-upload ftp