打开从asp.net的任何文件文件、asp、net

2023-09-07 09:23:16 作者:此夜此月

我如何可以打开任何文件,由指定的路径,在ASP.NET编程?

How can I open any file, specified by a path, in ASP.NET programatically?

我想下面的代码片段,但它读取打开文件,而不是文件的内容:

I tried the snippet below but it reads the contents of the file instead of opening the file:

string fileName = @"C:\deneme.txt";        
StreamReader sr = File.OpenText(fileName);        
while (sr.Peek() != -1)        
{            
    Response.Write(sr.ReadLine() + "<br>");        
}        
sr.Close();

我也试过 File.open方法方法

推荐答案

您可以的Response.Redirect 来,如果你只是opeining其文件

You can Response.Redirect to file if you're just opeining it

如果文件被下载,你可以使用folling code;

or if file is being downloaded you can use the folling code;

    public void DownloadFile(string fileName)
    {
        Response.Clear();
        Response.ContentType = @"application\octet-stream";
        System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(FileName));
        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.WriteFile(file.FullName);
        Response.Flush();
    }