c# 在 FTP 服务器内上传 byte[]

Noo*_*Tom 3 c# arrays ftp

我需要在 FTP 服务器内上传一些数据。

按照 stackoverflow 的帖子,了解如何在其中上传文件和 FTP,一切正常。

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

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

为了实现这一目标,我执行以下操作:

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();
Run Code Online (Sandbox Code Playgroud)

现在发生的事情如下:

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

我想要传输的数据是字符串类型,这就是为什么我这样做 byte[] messageContent = Encoding.ASCII.GetBytes(message);

我究竟做错了什么?

此外:如果我用 ASCII.GetBytes 对日期进行编码,在远程服务器上我会有一个文本文件还是一个带有一些字节的文件?

谢谢你的任何建议

Tun*_*ung 5

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

while (total_bytes > 0)
{
    strm.Write(messageContent, 0, buffLength); 
    total_bytes = total_bytes - buffLength;
}
Run Code Online (Sandbox Code Playgroud)

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

while (total_bytes < messageContent.Length)
{
    strm.Write(messageContent, total_bytes , bufferLength);
    total_bytes += bufferLength;
}
Run Code Online (Sandbox Code Playgroud)