双重道歉 - 首先,我是 ASP.net 的新手,所以我确定这是一个非常幼稚的问题,其次,看起来已经有一百个关于 ASP.NET 中相对路径的问题.不幸的是 - 我找不到能回答我问题的答案。
背景 - 我正在处理需要能够访问 Excel 文件的 .ashx
文件。
当我在本地运行并使用文件的绝对路径时,一切正常。这是我的代码:
<%@ WebHandler Language="C#" Class="MyHandler" %>
using System;
... [a bunch more "usings..."]
using Microsoft.Office.Interop.Excel;
public class MyHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
string path = @"C:\Users\[...]\myExcelFile.xls";
Workbook theWorkbook;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
theWorkbook = app.Workbooks.Open(path);
但是,我想在服务器上运行它,并使用 myExcelFile.xls
的相对路径。
我的项目是这样设置的:
Main folder:
- Default.aspx
- myExcelFile.xls
- Web.config
- Global.asax
Styles folder
Scripts folder
Handler folder
- MyHandler.ashx (that's reading the Excel File)
bin folder
因此 - 您可以看到 Excel 文件位于应用程序的“根目录”中。
为了使路径相对,我尝试了以下但没有成功:
假设“relative”来自 myHandler.ashx:
string path = @"..\myExcelFile.xls":
假设 ~
指的是“root”:
string path = @"~\myExcelFile.xls";
只是猜测:
string path = @".\myExcelFile.xls";
只是绝望:
string path = "myExcelFile.xls";
这些都不起作用。
所以我在这里对 SO 做了一点研究,发现了 System.IO.Path.GetFullPath
。所以我尝试了:
string path = System.IO.Path.GetFullPath("myExcelFile.xls");
那没有用,但至少我可以看到 path
的值是 C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\PinpointTool-DC.xls
当然 - 我根本不明白 - 那条路径离我的项目所在的地方很远(这意味着我不明白 System.IO.Path.GetFullPath
做了什么...... .)
最后,我尝试了 Server.MapPath("myExcelFile.xls")
,但这根本不起作用(至少在本地):
Compiler Error Message: CS0103: The name 'Server' does not exist in the current context
那么,我怎样才能让它工作(最好是在本地和服务器上?)
最佳答案
虽然您可以使用 context.Server.MapPath
,您还可以使用您在 appSettings
部分的“web.config”文件中定义的路径,稍后在您的应用程序中读取它:
网络配置:
...
<appSettings>
<add key="myBasePath" value="C:\Some\Path" />
</appSettings>
...
在您的 ASHX 处理程序中,您可以编写如下内容:
...
string path = Path.Combine(
ConfigurationManager.AppSettings[@"myBasePath"],
@"myExcelFile.xls");
...
您可以(并且应该)为您的开发机器和生产环境设置不同的“web.config”文件。
第二个John Saunders' remark关于服务器上的 Office Interop,我强烈建议使用像这样的 decidated 库
我与他们两个都成功合作(尽管是商业方面的)。
关于c# - 在 .ashx 页面中使用文件的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15026919/