Upload a file to an FTP server from a string or stream(从字符串或流上传文件到 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 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从字符串或流上传文件到 FTP 服务器


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01