我有一个ASP.NET网站,我在其中从xml文件加载一些验证规则.此xml文件名没有路径信息,在库中进行了硬编码.(我知道硬编码名称并不好,但让我们在这个例子中使用它).
当我运行网站时,ASP.NET尝试在源路径中找到xml 文件,其中名称为硬编码的C#文件是.这对我来说完全令人难以置信,因为我无法理解在运行时我们是如何考虑将源路径作为解析不合格文件名的可能性.
// the config class, in C:\temp\Project.Core\Config.cs
public static string ValidationRulesFile {
get { return m_validationRulesFile; }
} private static string m_validationRulesFile = "validation_rules.xml";
// using the file name
m_validationRules.LoadRulesFromXml( Config.ValidationRulesFile, "Call" );
Run Code Online (Sandbox Code Playgroud)
以下是显示我们查找的路径与Config.cs相同的异常:
Exception Details: System.IO.FileNotFoundException:
Could not find file 'C:\temp\Project.Core\validation_rules.xml'.
Run Code Online (Sandbox Code Playgroud)
任何人都可以向我解释这个吗?我已经知道你应该如何处理ASP.NET中的路径,所以请不要回答解决方案.我真的很想理解这一点,因为它真的让我感到惊讶,而且它会让我感到困扰.
以下是LoadRulesFromXml的相关代码
public void LoadRulesFromXml( string in_xmlFileName, string in_type )
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( in_xmlFileName );
...
Run Code Online (Sandbox Code Playgroud)
看起来Cassini Web服务器获取VS设置的当前目录,实际上它设置为我的库项目的路径.我不确定VS究竟如何确定哪个项目用于路径,但这至少解释了发生了什么.谢谢乔.
Joe*_*Joe 14
如果您不提供路径,则文件访问通常会使用当前工作目录作为默认值.在ASP.NET中,这可能是您的Web应用程序目录.
依赖当前工作目录通常不是一个好主意,因此您可以使用Path.Combine指定不同的默认目录,例如一个相对于AppDomain.CurrentDomain.BaseDirectory的目录,它也是ASP.NET的Web应用程序目录.应用程序.
您应该明确地将路径添加到要打开的文件的名称.您也可以尝试跟踪当前的工作目录.
从Visual Studio运行Cassini时,当前目录继承了Visual Studio的工作目录:这似乎是你的情况.
即:
public void LoadRulesFromXml( string in_xmlFileName, string in_type )
{
// To see what's going on
Debug.WriteLine("Current directory is " +
System.Environment.CurrentDirectory);
XmlDocument xmlDoc = new XmlDocument();
// Use an explicit path
xmlDoc.Load(
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
in_xmlFileName)
);
...
Run Code Online (Sandbox Code Playgroud)