C # upload byte [] inside FTP server

I need to upload some DATA inside and FTP server.

After stackoverflow posts on how to upload FILE internally and FTP, everything works.

Now I am trying to improve my load.

Instead of collecting DATA, writing them to FILE, and then uploading the file to FTP, I want to collect DATA and upload them without creating a local file.

To do this, I do the following:

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

Now the following will happen:

  • I see how the client connects to the server
  • File created
  • no data transferred
  • at some point, the thread ends with closing the connection
  • If I check that the downloaded file is empty.

The DATA I want to transfer is STRING TYPE, so I do byte [] messageContent = Encoding.ASCII.GetBytes (message);

what am I doing wrong?

: ASCII.GetBytes, TEXT ?

+3
2

, , , :

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

, . 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();
+1

All Articles