Downloading and decompressing on-the-fly a Gzip file from a Ftp server in C#

Today, I write a method in C# allowing to connect to a Ftp server, download a file compressed in Gzip format and pass its content to a string. The file is decompressed on-the-fly that is no file is created and written on the local disk. The method is then invoked in the main method. The snippet is straightforward. It can easily be derived to suit specific needs.

using System;
using System.IO;
using System.Net;
using System.Text;
using System.IO.Compression;

namespace WxDatabaseBuilder

class FtpClass

public void FtpFzipDownload (
string ftphost,
string ftpfilepath,
string userid,
string password)
// Targeted file and server
string ftpfullpath = ftp:// + ftphost + ftpfilepath;

// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpfullpath);
request.Method = WebRequestMethods.Ftp.DownloadFile;

// Deal with the FTP credentials
request.Credentials = new NetworkCredential(userid, password);

// Get a stream from the server
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();

// Gzip decompress
GZipStream gz = new GZipStream(responseStream, CompressionMode.Decompress);

// Get the content of the decompressed file into a string
StreamReader reader = new StreamReader(gz, Encoding.UTF8);

string result = reader.ReadToEnd();



class Program
public static void Main()
// Create an instance of Ftpclass class
FtpClass myFtp = new FtpClass();

// Value assignments
string myFtphost = ftp.blabla/; // targeted Ftp server ending
//with a slash mark
string myFtpfilepath = otherblabla.gz; // the targeted *.gz file
string myUserID = myfirstname; // username
string myPassword = secretcode; // password

// Invoke the method
myFtp.FtpFzipDownload(myFtphost, myFtpfilepath, myUserID, myPassword);

// Prevent the console window from closing down


About these ads