如何使用其应用程序打开文件(该文件不存在于Web服务器中)?

我想问一下如何在点击特定的链接按钮或超链接时打开一个特定的文件(该文件在服务器之外,我有一个存储在配置文件中的相对路径)及其应用程序…

喜欢 :

开盘

.docx用词。

要么

.pdf与acrobat阅读器

我尝试了几种方法但是,我得到了不同的错误

无法使用前导..退出顶级目录

我的.cs:

public void ProcessRequest(HttpContext context) { int newsId = int.Parse(context.Session["newsId"].ToString()); int FK_UnitId = int.Parse(context.Session["UserData"].ToString()); string dirPathForTextFiles = ConfigurationManager.AppSettings.GetValues("ThePath").First() + "/" + "NewsTextFiles" + "/" + "UnitNum" + FK_UnitId.ToString() + "_" + "NewsNum" + newsId + "/"; DataTable UpdatedDateTable = (DataTable)context.Session["theLastUpdatedTextFile"]; UpdatedDateTable.AcceptChanges(); context.Session.Add("currentTextFile", UpdatedDateTable); List l = new List(UpdatedDateTable.Rows.Count); try { l.Add(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString()); context.Response.ContentType = getContentType(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString()); System.Diagnostics.Process.Start(l[0]); context.ClearError(); } catch (IOException e) { string message = e.Message; } } string getContentType(String path) { switch (Path.GetExtension(path)) { case ".doc": return " application/msword"; case ".docx": return "application/msword"; case ".pdf": return "application/pdf"; default: break; } return ""; } 

为了获得服务器上的完整文件路径,您需要使用Server.MapPath。

 string fullFileName = Server.MapPath("../myFile.pdf"); 

编辑 :之后你需要Process对象来“运行”它:

 System.Diagnostics.Process.Start(fullFileName); 

编辑2 :如果您希望在客户端打开文件,最好的办法是创建HTTP Handler并在响应之前设置适当的mime类型 ,然后再将其从处理程序中流出。

编辑3 :将文件流式传输到客户端的代码。

 public void ProcessRequest(HttpContext context) { int newsId = int.Parse(context.Session["newsId"].ToString()); int FK_UnitId = int.Parse(context.Session["UserData"].ToString()); string dirPathForTextFiles = ConfigurationManager.AppSettings.GetValues("ThePath").First() + "/" + "NewsTextFiles" + "/" + "UnitNum" + FK_UnitId.ToString() + "_" + "NewsNum" + newsId + "/"; DataTable UpdatedDateTable = (DataTable)context.Session["theLastUpdatedTextFile"]; UpdatedDateTable.AcceptChanges(); context.Session.Add("currentTextFile", UpdatedDateTable); List l = new List(UpdatedDateTable.Rows.Count); try { l.Add(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString()); context.Response.ContentType = getContentType(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString()); using (FileStream fs = new FileStream(l[0], FileMode.Open, FileAccess.Read)) { long chunkSize = fs.Length; byte[] buf = new byte[chunkSize]; int bytesRead = 1; bytesRead = fs.Read(buf, 0,(int)chunkSize); if (bytesRead > 0) context.Response.OutputStream.Write(buf, 0, buf.Length); context.Response.OutputStream.Flush(); } } catch (IOException e) { string message = e.Message; } } 

System.Diagnostics.Process.Start(“启动FilePath”)