Open any file from asp.net

倖福魔咒の 提交于 2020-01-11 09:37:09

问题


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

I also tried the File.Open method.


回答1:


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

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



回答2:


If you want the file to be opened on the client side,Create an HTTP Handler and set the appropriate mime type on your response before streaming it out from your handler.

for more information I ask question near to your one before.

how to open file with its application



来源:https://stackoverflow.com/questions/6733136/open-any-file-from-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!