問題描述
我正在嘗試在 FTP 服務(wù)器上創(chuàng)建一個文件,但我所擁有的只是一個字符串或數(shù)據(jù)流以及創(chuàng)建它時應(yīng)使用的文件名.有沒有辦法從流或字符串在服務(wù)器上創(chuàng)建文件(我沒有創(chuàng)建本地文件的權(quán)限)?
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()) { }
推薦答案
只需將你的流復(fù)制到 FTP 請求流:
Just copy your stream to the FTP request stream:
Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();
對于一個字符串(假設(shè)內(nèi)容是一個文本):
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);
}
如果內(nèi)容是文本,則應(yīng)使用文本模式:
If the contents is a text, you should use the text mode:
request.UseBinary = false;
這篇關(guān)于從字符串或流上傳文件到 FTP 服務(wù)器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!