Question

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;
        }
    }
Was it helpful?

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.

OTHER TIPS

Does the site require a login and it's really redirecting you?

I've had one before that required me faking my browsing movements (and storing cookies and such) before it would allow me to download a file I needed.

Sorry, what does "the webpage" mean in "the contents of the webpage". There's only one URL involved here, which is myURL. Does myURL point to the CSV file directly? If so, then what does the contents that you are receiving actually look like?

Also:

if (File.Exists(CSVfile))
    downloadOk = true;
else
    downloadOk = false;

...is embarrassing. Please write:

downloadOk = File.Exists(CSVfile);

That has identical results, in 1 line instead of 4.

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

That is even worse. The single line:

return downloadOk;

...does exactly the same thing in 1 line of code instead of 7.

Also, both lines in your exception block...

catch (Exception error)
{
    downloadOk = false;
    string err = error.Message;
}

...do absolutely nothing. downloadOk will always be false in your exception block, and the local variable "err" is never used before it goes out of scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top