从字符串或流上传文件到 FTP 服务器 [英] Upload a file to an FTP server from a string or stream

查看:23
本文介绍了从字符串或流上传文件到 FTP 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 FTP 服务器上创建一个文件,但我所拥有的只是一个字符串或数据流以及创建它时应使用的文件名.有没有办法从流或字符串在服务器上创建文件(我没有创建本地文件的权限)?

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()) { }

推荐答案

只需将你的流复制到 FTP 请求流:

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

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
}

或者甚至更好地使用 StreamWriter:

Or even better use the StreamWriter:

using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
    writer.Write(data);
}

如果内容是文本,则应使用文本模式:

If the contents is a text, you should use the text mode:

request.UseBinary = false;

这篇关于从字符串或流上传文件到 FTP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆