首先,我将介绍项目结构:打开一个Word文档与C#中的相对路径在asp.net
- 解决方案
- 模板
- 体育
- Sport.doc
- 体育
- 模板
- Opendoc.aspx
- Opendoc.aspx.cs
现在的问题。 在Opendoc.aspx.cs中,我试图打开Sport.doc,但是当我使用相对路径时不工作。只有当我硬编码它像c://Sport.doc。
后,我点击该网页我去这种方法上的一个按钮:
protected void btnCreateWordBulletin_Click(object sender, EventArgs e)
{
string path = VirtualPathUtility.ToAbsolute("~/Sport/Sport.doc");
string Savepath = VirtualPathUtility.ToAbsolute("~/Sport/SportEvent.doc");
CreateWordDocument(path, Savepath);
}
protected void CreateWordDocument(object fileName, object saveAs)
{
//Set Missing Value parameter - used to represent
//a missing value when calling methods through interop
object missing = System.Reflection.Missing.Value;
//Setup the Word.App class
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document aDoc = null;
// Check to see that file exists
if (System.IO.File.Exists((string)fileName))
{... Activating doc etc...}}
但System.IO.File.exists似乎并没有找到该文件。
我试过使用.//Sport/sport.doc,../Sport.doc,.//Template/Sport/sport.doc,////Template/Sport.doc。
你能解释一下我应该如何使用它?它告诉我错误非静态字段,方法或属性'System.Web.HttpApplication.Server.get'需要对象引用 – Liquid 2011-05-06 13:42:31
是的,当然,这会将Parameter1中指定的路径附加到当前的ServerPath( =你的解决方案的路径)。您还需要将参考'System.Web'添加到您的Using-block。此外,由于这返回一个字符串值,所以你需要将它分配给某些东西,例如'string a = Server.MapPath(“/”);'。如果这不起作用(它在CodeBehind-File中对我来说),请改用'HttpApplication.Current.Server.MapPath(“/”)'。 – 2011-05-06 13:47:29
Duh,我的意思是'HttpContext.Current.Server.MapPath(“/”);'当然。注意:这不适用于异步方法。 – 2011-05-06 13:54:40