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

时间:2012-05-07 08:44:43

标签: c# ftp bytearray

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

关于如何在里面上传文件的Stackoverflow帖子和FTP一切正常。

现在我正在尝试改善上传。

而是收集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. 如果我检查上传的文件是空的。
  6. 我要传输的DATA是STRING TYPE,这就是我做byte [] messageContent = Encoding.ASCII.GetBytes(message);

    的原因

    我做错了什么?

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

    感谢您的任何建议

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

您正在尝试编写比您更多的数据。您的代码一次写入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();