C# ASP.NET 应用程序代码中的相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9603092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:05:08  来源:igfitidea点击:

Relative paths in an ASP.NET application code behind

c#asp.net.net

提问by kmarks2

Being new to ASP.NET I'm unsure of the best solution to my problem. I have a line of code like:

作为 ASP.NET 的新手,我不确定我的问题的最佳解决方案。我有一行代码,如:

xDoc.Load("Templates/template1.cfg");

xDoc is an XmlDocument. In my project, at the top level there is a directory called Templates. When I run the project in debug mode, I get a DirectoryNotFoundException, and apparently it's looking for the Templates dir in C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\Templates.

xDoc 是一个XmlDocument. 在我的项目中,顶层有一个名为 Templates 的目录。当我在调试模式下运行项目时,我得到一个DirectoryNotFoundException,显然它正在C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\Templates.

How can correctly point to that directory without hardcoding it?

如何在没有硬编码的情况下正确指向该目录?

采纳答案by Adrian Iftode

Server.MapPath- returns the path of the relative path; ~ensures the relative path is related to the application root

Server.MapPath- 返回相对路径的路径;~确保相对路径与应用程序根相关

xDoc.Load(Server.MapPath("~/Templates/template.cfg"));

回答by mattematico

xDoc.Load("~/Templates/template.cfg");

might work?

可能有用吗?

回答by Khan

Use a tilde "~" in your path.

在您的路径中使用波浪号“~”。

xDoc.Load("~/Templates/template1.cfg");

The tilde represents the base directory for your application.

波浪号代表您的应用程序的基本目录。

回答by Joe

I would probably use

我可能会用

xDoc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates", "Template.cfg"));

This makes your XML loading code independent of ASP.NET. If you were to reuse it in, say, a Windows Forms application, this would give a path relative to the directory containing the Windows Forms exectuable.

这使您的 XML 加载代码独立于 ASP.NET。如果您要在 Windows 窗体应用程序中重用它,这将给出一个相对于包含 Windows 窗体可执行文件的目录的路径。

回答by JDunkerley

Try:

尝试:

xDoc.Load(Server.MapPath("~/Templates/template1.cfg"));