从字符串或流上传文件到FTP服务器
本文关键字:文件 FTP 服务器 字符串 | 更新日期: 2023-09-27 18:04:46
我试图在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请求流:
Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();
对于字符串(假设内容是文本):
byte[] bytes = Encoding.UTF8.GetBytes(data);
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
或者更好地使用StreamWriter
:
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
writer.Write(data);
}
如果内容是文本,你应该使用文本模式:
request.UseBinary = false;
设置此参数用于将xml文件发送到FTP。它工作得很好。我想这正是你所需要的。
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://XXXXXXXXXX//" + filename);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user", "pwd");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
StreamReader sourceStream = new StreamReader(file);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
问候!