0

i need to change the logic in an old system and im trying to get the downloading file to work, any ideas? i need to download the files using ftp in c# this is the code i found but i need to get that into a file instead of a stream

// Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.1.52/Odt/"+fileName+".dat");
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        Console.WriteLine(reader.ReadToEnd());

        Console.WriteLine("Download Complete, status {0}", response.StatusDescription);

        reader.Close();
        response.Close();  
luis urdaneta
  • 21
  • 1
  • 2
  • 2
    So instead of writing the stream to the console, write it to the file, something like `File.WriteAllText(@"c:\somefile.txt", reader.ReadToEnd());` – Ron Beyer May 15 '15 at 13:46
  • @MartinPrikryl: your proposed duplicate uses `FtpClient`, not `FtpWebRequest`. It's similar, but it would require significant effort for the OP to apply the information there to his own problem. – Peter Duniho May 16 '15 at 05:33

1 Answers1

0

The suggestion from commenter Ron Beyer isn't bad, but because it involves decoding and re-encoding the text, there is a risk of data loss.

You can download the file verbatim by simply copying the request response stream to a file directly. That would look something like this:

// Some file name, initialized however you like
string fileName = ...;

using (Stream responseStream = response.GetResponseStream())
using (Stream fileStream = File.OpenWrite(filename))
{
    responseStream.CopyTo(fileStream);
}

Console.WriteLine("Download Complete, status {0}", response.StatusDescription);

response.Close();
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136