Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c# - Upload a file to an FTP server from a string or stream

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()) { }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...