Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用HttpWebRequest下载阅读问题的文件_C#_Httpwebrequest - Fatal编程技术网

C# 使用HttpWebRequest下载阅读问题的文件

C# 使用HttpWebRequest下载阅读问题的文件,c#,httpwebrequest,C#,Httpwebrequest,如果我有下载的URL,www.website.com/myfile.html 因此,当单击该链接时,它会自动开始下载,例如,可能是myfile.txt,我如何将该文件导入C#以便阅读 这就是Net.WebRequest.Create(url),Net.HttpWebRequest所做的吗?您可以通过以下方法实现: 如果不想将文件存储在本地,而只读取内容,可以尝试以下方法: using (var client = new WebClient()) { string result = cli

如果我有下载的URL,
www.website.com/myfile.html
因此,当单击该链接时,它会自动开始下载,例如,可能是
myfile.txt
,我如何将该文件导入C#以便阅读


这就是
Net.WebRequest.Create(url)
Net.HttpWebRequest
所做的吗?

您可以通过以下方法实现:

如果不想将文件存储在本地,而只读取内容,可以尝试以下方法:

using (var client = new WebClient())
{
    string result = client.DownloadString("http://www.website.com/myfile.html");
}
以C#为例,下面是一个如何在单击按钮、链接等后强制下载文件的过程

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

记住这一点,您需要查找响应中的标题,标题将包含一个项目内容处置,其中将包含响应中正在流式传输的文件名。

如果.html文件只是下载的链接,这是否仍然有效?对于我的链接,当我访问浏览器中的url时,它会自动开始下载。这取决于。如果页面上有javascript,那么它将无法工作。您需要将请求伪造为最终url,以便下载文件。
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();
}