我需要从 App_Data 文件夹打开文件,我发现了这个代码片段,只是想知道这个代码是否经过优化。
I 文件的类型可以是 .docx、doc、.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);
请推荐我应该使用哪种方法。我想要简单的是用户单击链接以打开文档。此链接通过电子邮件发送给用户。
更新
我实际上想知道使用过的对象是否正确关闭以及此代码是否以正确的方式处理