在FTP服务器上上传一个 byte[] 的 C# 文件

3

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

按照stackoverflow的帖子上传文件,一切正常。

现在,我正在尝试改进我的上传。

我想收集数据并上传它们,而不是先将它们写到一个文件中,然后将该文件上传到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();

现在发生的情况如下:
  1. 我看到客户端正在连接服务器
  2. 文件已创建
  3. 没有传输数据
  4. 在某个点上线程被终止,连接被关闭
  5. 如果我检查上传的文件是空的。
我想传输的数据是字符串类型,所以我做了 byte[] messageContent =Encoding.ASCII.GetBytes(message);
我错在哪里了?
此外:如果我使用ASCII.GetBytes编码日期,在远程服务器上将会得到一个文本文件还是一些字节的文件?
谢谢任何建议。

strm.Write(messageContent, 0, messageContent.lenght); 就是解决方案。就像这样,我认为会一次性写入整个文件,但我不知道对于大文件会发生什么。 - NoobTom
2个回答

5

我看到这段代码中的一个问题是你在每次循环时都向服务器写入相同的字节:

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;
}

2

你在尝试写入比你实际数据量更多的数据。你的代码每次会写入2048个字节的块,并且如果数据少于这个量,你会告诉write方法去尝试访问数组之外的字节,当然这是不行的。

你所需写入的数据如下:

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

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

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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接