获取asp.net mvc中的当前目录

发布于 2025-01-08 08:08:33 字数 430 浏览 0 评论 0原文

我正在尝试构建一个文件路径以读取 XSLT 文件,如下所示:

string path = "../_xslt/example.xslt";
StreamReader reader = new StreamReader(path); 

...我位于控制器 (/Controllers/ExampleController.cs) 中,并且“/_xslt/”文件夹位于同一级别as '/Controllers'

但是,我收到的错误是:

(系统.IO.DirectoryNotFoundException) 找不到路径“c:\windows\system32\_xslt\example.xslt”的一部分。

我是否以错误的方式处理这个问题?

感谢您的帮助!

I am trying to construct a file path in order to read an XSLT file, like so:

string path = "../_xslt/example.xslt";
StreamReader reader = new StreamReader(path); 

...where I am in a controller (/Controllers/ExampleController.cs), and the '/_xslt/' folder is at the same level as '/Controllers'

However, the error I am getting is:

(System.IO.DirectoryNotFoundException)
Could not find a part of the path 'c:\windows\system32\_xslt\example.xslt'.

Am I going about this the wrong way?

Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

短叹 2025-01-15 08:08:33

您可以使用 HttpServerUtility.MapPath 方法来映射任何相对路径在你的控制器中,这可以通过 ControllerContext 轻松访问:

string path = ControllerContext.HttpContext.Server.MapPath("~/_xslt/example.xslt");
...

You can use the HttpServerUtility.MapPath method to map any relative paths for you, in your controller this is easily accessible via the ControllerContext:

string path = ControllerContext.HttpContext.Server.MapPath("~/_xslt/example.xslt");
...
谁的年少不轻狂 2025-01-15 08:08:33
string TestX()
{
    string path = AppDomain.CurrentDomain.BaseDirectory; // You get main rott
    string dirc = ""; // just var for use
    string[] pathes = Directory.GetDirectories(path); // get collection

    foreach (string str in pathes)
    {
        if (str.Contains("NameYRDirectory")) // paste yr directory
        {
            dirc = str;
        }
    }

    return dirc; // after use Method and modify as you like
}
string TestX()
{
    string path = AppDomain.CurrentDomain.BaseDirectory; // You get main rott
    string dirc = ""; // just var for use
    string[] pathes = Directory.GetDirectories(path); // get collection

    foreach (string str in pathes)
    {
        if (str.Contains("NameYRDirectory")) // paste yr directory
        {
            dirc = str;
        }
    }

    return dirc; // after use Method and modify as you like
}
谜兔 2025-01-15 08:08:33

如果控制器存在于目录根目录

String path = ControllerContext.HttpContext.Server.MapPath(@"~/_xslt/example.xslt");

否则

String path = ControllerContext.HttpContext.Server.MapPath(@"../_xslt/example.xslt");

If controller is present at directory root

String path = ControllerContext.HttpContext.Server.MapPath(@"~/_xslt/example.xslt");

Else

String path = ControllerContext.HttpContext.Server.MapPath(@"../_xslt/example.xslt");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文