开发者

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.WebRe开发者_Python百科quest.Create(url), Net.HttpWebRequest does?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜