Upload a file to an FTP server from a string or stream
Asked Answered
C

2

11

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()) { }
Chandrachandragupta answered 30/8, 2016 at 10:25 Comment(0)
D
11

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;
Dacia answered 30/8, 2016 at 12:0 Comment(0)
V
0

i make this for send a xml file to a FTP. It works fine. I thinks is what you need.

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

Regards!

Vulva answered 30/8, 2016 at 10:37 Comment(1)
That's not a generic solution. You convert the contents to UTF-8. So it can work with text files only. And you didn't state this limitation. Moreover, using a binary mode for text files does not seem right.Dacia

© 2022 - 2024 — McMap. All rights reserved.