HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

FTP Download Function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
downloadfunctionftp

Problem

This is an function that downloads a single file from an FTP server and saves it to disk
This is my first time doing anything with FTP, please let me know if i have missed anything.

public void DownloadFile(string fileloc, string saveLoc)
{
    try
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(fileloc);
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        request.Credentials = new NetworkCredential(Username, Password);

        using (var response = (FtpWebResponse)request.GetResponse())
        {
            using (var fileStream = File.Create(saveLoc))
            {
                response.GetResponseStream().CopyTo(fileStream);
            }
        }
    }
    catch (Exception EX)
    {
        throw EX;               
    }
}

Solution

First, like ANeves said, the only thing your catch does is that it resets the exception's stack trace, which is not what you want to do. Just remove the try/catch completely, it serves no purpose here.

Second, I don't see any reason to use WebRequest here, using WebClient is much simpler.

Also, you might want to have better parameter names: fileloc doesn't say what exactly it is, and doesn't use the usual capitalization. And loc is unnecessarily abbreviated (you're not trying to write a Twitter post where every character counts, readability is more important) and too ambiguous.

public void DownloadFile(string url, string savePath)
{
    var client = new WebClient();
    client.Credentials = new NetworkCredential(Username, Password);
    client.DownloadFile(url, savePath);
}


This method could be rewritten as one expression, but I probably wouldn't do that:

public void DownloadFile(string url, string savePath)
{
    new WebClient { Credentials = new NetworkCredential(Username, Password) }
        .DownloadFile(url, savePath);
}

Code Snippets

public void DownloadFile(string url, string savePath)
{
    var client = new WebClient();
    client.Credentials = new NetworkCredential(Username, Password);
    client.DownloadFile(url, savePath);
}
public void DownloadFile(string url, string savePath)
{
    new WebClient { Credentials = new NetworkCredential(Username, Password) }
        .DownloadFile(url, savePath);
}

Context

StackExchange Code Review Q#12697, answer score: 6

Revisions (0)

No revisions yet.