c#在FTP服务器中上传一个byte

我需要上传一些DATA和FTP服务器。

关于如何上传FILE内容和FTP一切正常的stackoverflowpost。

现在我正在努力改善我的上传。

而是收集DATA,将它们写入FILE然后在FTP中上传文件我想收集DATA并上传它们而不创建本地文件。

为此,我执行以下操作:

string uri = "ftp://" + ftpServerIp + "/" + fileToUpload.Name; System.Net.FtpWebRequest reqFTP; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIp + "/" + fileToUpload.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; byte[] messageContent = Encoding.ASCII.GetBytes(message); // Notify the server about the size of the uploaded file reqFTP.ContentLength = messageContent.Length; int buffLength = 2048; // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Write Content from the file stream to the FTP Upload Stream int total_bytes = (int)messageContent.Length; while (total_bytes > 0) { strm.Write(messageContent, 0, buffLength); total_bytes = total_bytes - buffLength; } strm.Close(); 

现在发生的是以下情况:

  1. 我看到客户端连接到服务器
  2. 文件已创建
  3. 没有数据传输
  4. 在某些时候线程终止连接被关闭
  5. 如果我检查上传的文件是空的。

我要传输的DATA是STRING TYPE,这就是我做byte [] messageContent = Encoding.ASCII.GetBytes(message);

我究竟做错了什么?

而且:如果我用ASCII.GetBytes编码日期,在远程服务器上我会有一个TEXT文件或带有一些字节的文件吗?

谢谢你的任何建议

我在代码中看到的一个问题是,您在每次迭代时向服务器写入相同的字节:

 while (total_bytes > 0) { strm.Write(messageContent, 0, buffLength); total_bytes = total_bytes - buffLength; } 

您需要通过执行以下操作来更改偏移位置:

 while (total_bytes < messageContent.Length) { strm.Write(messageContent, total_bytes , bufferLength); total_bytes += bufferLength; } 

您正在尝试编写比您更多的数据。 您的代码一次写入2048字节的块,如果数据较少,您将告诉write方法尝试访问数组外部的字节,当然它不会。

你需要写的所有数据是:

 Stream strm = reqFTP.GetRequestStream(); strm.Write(messageContent, 0, messageContent.Length); strm.Close(); 

如果需要以块的forms写入数据,则需要跟踪数组中的偏移量:

 int buffLength = 2048; int offset = 0; Stream strm = reqFTP.GetRequestStream(); int total_bytes = (int)messageContent.Length; while (total_bytes > 0) { int len = Math.Min(buffLength, total_bytes); strm.Write(messageContent, offset, len); total_bytes -= len; offset += len; } strm.Close();