Excel 文件放在項目根目錄,代碼中如何寫路徑?原代碼使用絕對路徑 @"E:\001.xls"。
E:\Project\001.xls,部署後失效。bin\Debug,發布後為安裝目錄。| 項目類型 | 獲取基準路徑 | 代碼示例 |
|---|---|---|
| WinForms / WPF / Console | 應用程序啟動目錄 | Application.StartupPath + "\\001.xls" |
| ASP.NET (WebForms/MVC) | 網站根目錄 | Server.MapPath("~/001.xls") 或 HttpContext.Current.Server.MapPath("~/001.xls") |
| ASP.NET Core | ContentRootPath | _env.ContentRootPath + "/001.xls" (注入 IWebHostEnvironment) |
bin\Debug。Path.Combine 組合路徑,跨平台兼容。// WinForms 通用寫法
string filePath = Path.Combine(Application.StartupPath, "001.xls");
if (File.Exists(filePath)) {
// 操作 Excel
}
搞清運行時基準目錄,路徑問題迎刃而解。