Upload a file to an FTP server from a string or stream

I am trying to create a file on an FTP server, but all I have is either a string or a data stream, and the name of the file with which it should be created. Is there a way to create a file on the server (I do not have permission to create local files) from a stream or line?

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()) { }
+4
source share
2 answers

Just copy the stream to the FTP request stream:

Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();

For a string (assuming the content is text):

byte[] bytes = Encoding.UTF8.GetBytes(data);

Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();

If the content is text, you should use text mode:

request.UseBinary = false;
+8
source

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

!

-1

Source: https://habr.com/ru/post/1652985/


All Articles