2011-07-18 41 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會使用什麼參數? –