我需要從App_Data文件夾中打開文件,並且發現此代碼段,只是想知道這段代碼是否已優化。從App_data文件夾中讀取文件的代碼優化
我的文件可以是類型的.docx,文檔,.PDF
try
{
string path = Server.MapPath("~/App_Data/File.txt");
//string = Server.MapPath(strRequest);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/....";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
catch (Exception rt)
{
// Response.Write(rt.Message);
}
或使用該代碼段
FileStream MyFileStream;long FileSize;
string path = Server.MapPath("~/App_Data/aspnetmvc-nerdinner_v1.pdf");
MyFileStream = new FileStream(path, FileMode.Open);
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize + 1];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=MyReport.PDF");
Response.BinaryWrite(Buffer);
請推薦哪種方法我應該使用。我想要的簡單就是用戶點擊鏈接打開文檔。這個鏈接通過電子郵件發送給用戶。
UPDATE
其實我是想知道,如果使用的對象是否正確關閉,如果這個代碼在一個適當的方式處置這裏
你有沒有考慮過使用'StopWatch'類來定時每個代碼片段? http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx –
@JasonEvans,我會研究一下。 – Learning
@JasonEvans,我實際上想知道如果使用的對象是正確關閉的,並且如果這個代碼在正確處理 – Learning