Matt
Matt

Reputation: 4190

Download file for reading question using HttpWebRequest

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?

Upvotes: 0

Views: 1060

Answers (2)

JoeGeeky
JoeGeeky

Reputation: 3796

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

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");
}

Upvotes: 1

Related Questions