Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Downloading a File - .NET Framework

RSS
Modified on Sat, Sep 26, 2009, 6:39 PM by Administrator Categorized as ┬ĚNet Framework
If all you want to do is to read the contents of a web page given its URL, the WebClient class will do the trick.

string contents = new WebClient().DownloadString(url);

Otherwise, here's a more complex way to do it.

public static void DownloadFile(string remoteUrl, string localFile, bool ignoreErrors)
{
    string errorDetail = "";
    string tempFile = localFile + ".tmp";
    try
    {
        errorDetail = "Couldn't delete downloaded file " + localFile;
        File.Delete(tempFile);
    }
    catch { }

    try
    {
        errorDetail = "Couldn't download file " + tempFile;

        if (DOWNLOAD_VIA_BROWSER)
        {
            WebBrowser browser = new WebBrowser();

            browser.DocumentCompleted 
                += new WebBrowserDocumentCompletedEventHandler(
                browser_DocumentCompleted);

            browser.Navigate(remoteUrl);
            _browser_working = true;

            while (_browser_working) 
                Application.DoEvents();

            StreamReader reader = new StreamReader(browser.DocumentStream);

            string s = reader.ReadToEnd();

            File.WriteAllText(tempFile, s);
        }
        else
        {
            new WebClient().DownloadFile(remoteUrl, tempFile);
        }

        File.Delete(localFile);
        File.Move(tempFile, localFile);
    }
    catch (Exception ex)
    {
        if (!ignoreErrors)
        {
            ExceptionHandler.Show(ex, errorDetail);
            throw ex;
        }
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.