将文件从字符串或流上传到FTP服务器 [英] Upload a file to an FTP server from a string or stream
本文介绍了将文件从字符串或流上传到FTP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在FTP服务器上创建一个文件,但我所拥有的只是一个字符串或数据流以及它应该创建的文件名。有没有办法在服务器上创建文件(我没有创建本地文件的权限)?
string location =ftp://xxx.xxx.xxx.xxx:21/TestLocation/Test.csv;
WebRequest ftpRequest = WebRequest.Create(location);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(userName,password);
string data = csv.getData();
MemoryStream stream = csv.getStream();
// Magic
using(var response =(FtpWebResponse)ftpRequest.GetResponse()){}
解决方案
只需将您的流复制到FTP请求流即可:
p> Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();
对于一个字符串(假设内容是文本):
byte [] bytes = Encoding.UTF8.GetBytes(data);
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes,0,bytes.Length);
requestStream.Close();
如果内容是文本,则应使用文本模式:
request.UseBinary = false;
I'm trying to create a file on an FTP server, but all I have is either a string or a stream of the data and the filename it should be created with. Is there a way to create the file on the server (I don't have permission to create local files) from a stream or string?
string location = "ftp://xxx.xxx.xxx.xxx:21/TestLocation/Test.csv";
WebRequest ftpRequest = WebRequest.Create(location);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(userName, password);
string data = csv.getData();
MemoryStream stream = csv.getStream();
//Magic
using (var response = (FtpWebResponse)ftpRequest.GetResponse()) { }
解决方案
Just copy your stream to the FTP request stream:
Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();
For a string (assuming the contents is a text):
byte[] bytes = Encoding.UTF8.GetBytes(data);
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
If the contents is a text, you should use a text mode:
request.UseBinary = false;
这篇关于将文件从字符串或流上传到FTP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文