views:

46

answers:

2

If I have a URL to a download, www.website.com/myfile.html so when that link is clicked it automatically starts a download, which may be myfile.txt for example, how would I get that file into C# for reading..

Is that what Net.WebRequest.Create(url), Net.HttpWebRequest does?

+1  A: 

You could achieve this using WebClient:

using (var client = new WebClient())
{
    // Download and save the file locally
    client.DownloadFile("http://www.website.com/myfile.html", "myfile.html");
}

If you don't want to store the file locally but only read the contents you could try this:

using (var client = new WebClient())
{
    string result = client.DownloadString("http://www.website.com/myfile.html");
}
Darin Dimitrov
does this still work if the .html file is just a link to the download?For my link, when I visit the url in my browser, it automatically starts a download..
Matt
It depends. If there's javascript on the page then it won't work. You will need to forge the request to the final url allowing you to download the file.
Darin Dimitrov
A: 

Using C# as an example, here is how one might force the download of a file after clicking a button, link, etc...

public void DownloadFileLink_Click(object sender, EventArgs e)
{
    //Get the file data
    byte[] fileBytes = Artifacts.Provider.GetArtifact(ArtifactInfo.Id);

    //Configure the response header and submit the file data to the response stream.
    HttpContext.Current.Response.AddHeader("Content-disposition", "attachment;filename=" + "myDynamicFileName.txt");
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.BinaryWrite(fileBytes);
    HttpContext.Current.Response.End();
}

With this in mind, what you need to look for is the Header in the response, the Header will contain an item Content-disposition which will contain the filename of the file being streamed in the response.

JoeGeeky