C#上传一个byte [] FTP服务器内 [英] c# upload a byte[] inside an FTP server
问题描述
我需要内部和FTP服务器上传一些数据。
I need to upload some DATA inside and FTP server.
下面就如何上传中的文件和FTP一切正常计算器的帖子。
Following stackoverflow posts on how to upload a FILE inside and FTP everything works.
现在我正在努力提高我的上传
Now i am trying to improve my upload.
而不是收集数据,将其写入一个文件,然后上传文件中的。FTP我想收集数据,并将其上传而不创建本地文件
Instead collecting the DATA, writing them to a FILE and then upload the file inside the FTP i want to collect the DATA and upload them without creating a local file.
要做到这一点我做到以下几点:
To achieve 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();
现在什么情况如下:
- 我看到客户端连接到服务器
- 创建文件
- 没有数据传输
- 在某些时候线程终止连接关闭
- 如果我检查上传的文件是空的。
- i see the client connecting to the server
- the file is created
- no data are transferred
- at some point the thread is terminated the connection is closed
- if i inspect the uploaded file is empty.
我要来传输数据是一个字符串类型,这就是为什么我做的byte [] = messageContent的Encoding.ASCII.GetBytes(消息);
the DATA i want to to transfer is a STRING TYPE, that is why i do byte[] messageContent = Encoding.ASCII.GetBytes(message);
我究竟做错了
另外:如果我编码日期ASCII.GetBytes,在远程服务器上会我有一个文本文件或一些字节的文件?
moreover: if i encode date with ASCII.GetBytes, on the remote server will i have a TEXT file or a file with some Bytes?
感谢您的任何建议。
推荐答案
一个问题,我的代码看到的是,你正在写在相同字节到服务器上的每个迭代:
One issue that I see with the code is that you are writing the same bytes to the server on each iteration:
while (total_bytes > 0)
{
strm.Write(messageContent, 0, buffLength);
total_bytes = total_bytes - buffLength;
}
您需要通过做这样的事情来改变偏移位置>
You need to change the offset position by doing something like this:
while (total_bytes < messageContent.Length)
{
strm.Write(messageContent, total_bytes , bufferLength);
total_bytes += bufferLength;
}
这篇关于C#上传一个byte [] FTP服务器内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!