2011-07-18 37 views
2

如何以编程方式在ASP.NET中打开由路径指定的任何文件?从asp.net打开任何文件

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

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

我也尝试了File.Open method

+0

如果没有阅读内容,你究竟在做什么? – ChrisBint

+0

你想要做什么?获取文件内容为字符串?以流的形式打开文件?获取文件内容为byte []? – Emiswelt

+2

问题是什么?你想做什么? File.Open将打开一个文件 - 你有一个具体的问题吗?一旦文件打开,你在做什么? –

回答

2

可以Response.Redirect到文件,如果你只是opeining它

,或者如果文件被下载,你可以使用folling代码;

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

@Xor:你试过这个吗? – Grace

+1

+1。重定向工作不好,因为它不设置200 HTTP状态。但方法很棒! – VMAtm

+0

@saj:response.redirect会使用什么参数? –