Search code examples
c#webclient

DownloadFile from the Internet?


I'm confused with the code block below because why it downloads the contents of the webpage rather the file itself. I create dummy file with some texts in it then I download it, but when I open the download file, I don't see any text that I wrote but it has weird web language tags.

    private bool DownloadCSVfile()
    {
        bool downloadOk = false;
        WebClient client = null;

        try
        {
            client = new WebClient();
            client.Credentials = CredentialCache.DefaultCredentials;
            client.DownloadFile(myURL, CSVfile);

            if (File.Exists(CSVfile))
                downloadOk = true;
            else
                downloadOk = false;
        }
        catch (Exception error)
        {
            downloadOk = false;
            string err = error.Message;
        }

        //release resource
        if (client != null)
        {
            client.Dispose();
            client = null;
        }

        //
        if (downloadOk == true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Solution

  • I'm guessing myURL ends in "/" and not ".csv" Am I right? Are you thinking that myURL + CSVFile will contain the full path to the file? It won't. (See doc) The URL has to be the path to the file itself. You are allowed to have something like this:

    client.DownloadFile(@"./file.csv", "filename.txt");
    

    If I'm not on the right track, please tell what's in the URL and what some of the first several tags are in the downloaded file.