首先,我將介紹項目結構:打開一個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