Follow by Email

Wednesday, August 28, 2013

download an excel file from a ftp in c#.net | Download file from ftp example in .net

hi in this post i will show how to download an excel file from a ftp in c#.net.

Below is the code:

    public void Main()
    {
        // FTP URL
        FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://www.yourDomainNameorIP/ExcelFile.xlsx");
        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

        // FTP Login
        ftpRequest.Credentials = new NetworkCredential("<UserId>", "<Pwd>");

        FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

        Stream responseStream = ftpResponse.GetResponseStream();
        long cl = ftpResponse.ContentLength;

        int bufferSize = 2048;
        int readCount;

        byte[] buffer = new byte[bufferSize];

        String FilePath;
        FilePath = Server.MapPath("/Download"); // create a folder called Download in the application root folder to save the file.

        FileStream outputStream = new FileStream(FilePath + "\\" + "filename.xlsx", FileMode.Create);

        readCount = responseStream.Read(buffer, 0, bufferSize);

        while (readCount > 0)
        {
            outputStream.Write(buffer, 0, readCount);
            readCount = responseStream.Read(buffer, 0, bufferSize);
        }

        responseStream.Close();
        outputStream.Close();
        ftpResponse.Close();
    }


After u execute the above code u can see the downloaded file in the download folder created in the root folder of the application.