Search code examples
c#batch-fileftpibm-midrange

C# Download File from FTP AS400


we currently have a *.BAT file that contains some FTP commands to download a file from our AS400 and save into a TEXT file. The BAT works fine and the text file will show the records inside the downloaded file one under the other.

Now, we wanted to get rid of this *.BAT file and use C# to download the file for us and save into a text file. The problem now is that the file we get contains all the records in ONE single line of string! they are no longer listed under each other.

here is the code we are using:

tpWebRequest request = default(FtpWebRequest);
        FtpWebResponse response = default(FtpWebResponse);
        StreamWriter writer = default(StreamWriter);

        request = WebRequest.Create("*******URL******") as FtpWebRequest;

        request.Credentials = new NetworkCredential("user", "pass");

        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.UseBinary = true;

        response = request.GetResponse() as FtpWebResponse;

        writer = new StreamWriter(Server.MapPath("/filename.txt"));

        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(37))) //37 for IBM encoding
        {
            writer.WriteLine(reader.ReadToEnd());
        }

        writer.Close();

        response.Close();

Any idea why we are getting this? and why the simple DOS FTP command work better than our code?

Thanks a lot! :)


Solution

  • ASCII mode will add record delimiters when downloading a physical file. It is the default transfer mode of most ftp clients.

    request.UseBinary = false;
    

    Specifying false causes the FtpWebRequest to send a "Type A" command to the server.

    Data Transfer Methods

    Transferring QSYS.LIB files