使用相对路径检查文件是否存在
使用相对路径检查文件是否存在的最佳方法是什么。
我使用了以下方法,但尽管文件存在,它仍然返回false。
bool a = File.Exists("/images/Customswipe_a.png");
那不是一条相对的道路。 你需要先离开第一个/
否则它将被解释为root(即C:/ images ……)
我猜你在asp.net应用程序中运行这段代码,这就是你弄错的原因。
在asp.net中,您应该使用Server.MapPath("/images/Customswipe_a.png")
来获取“正确”路径(相对于Web应用程序根目录)。 否则,您将获得Web服务器可执行文件的本地路径(IIS / WEBDAV / ..其他任何名称)。
相对路径相对于当前工作目录。 它可能不是应用程序目录。 调用GetCurrentDirectory()来检查您正在测试的实际路径。
您只需要定义文件的相对内容
- 你的应用主要组件?
- 目前的目录?
- 应用数据目录?
- 把它命名……
在每种情况下,我建议您通过Path.Combine
方法将其转换为绝对路径:
public static readonly string AppRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); ... //calling with a '/' heading makes the path absolute so I removed it var fullPath = Path.Combine(AppRoot, "images/Customswipe_a.png"); var exists = File.Exists(fullPath);
这样您就可以保证在哪里寻找。 即使打开/保存文件对话框也可能会更改当前目录。 因此, File.Exists
没有完整路径的情况下调用File.Exists
通常是一个错误的决定。
相对路径,是相对于某事物。 在这个API中,它将根据文档File.Exists :
相对路径信息被解释为相对于当前工作目录。
所以这里的一切都取决于执行此查询时CurrentDirectoty的内容。
另外,您的路径无效桌面路径(我假设您从某个Web文件或知识中选择它)。 要了解指定的路径是否包含无效字符,请使用GetInvalidCharacters函数。
在您的具体情况下,使用@"\images\Customswipe_a.png"
就足够了。
您可以使用System.IO.DirectoryInfo测试此路径:
DirectoryInfo info = new DirectoryInfo("/images/Customswipe_a.png"); string absoluteFullPath = info.FullName;
正如Mike Park正确回答的那样,这条路很可能就是(即C:/ images ……)
该路径相对于二进制文件的位置。 对于visual studio项目,这将是%PROJECTDIR%/bin/(RELEASE||DEBUG)/
我要做的是将文件系统root置于配置文件中,并将其用于相对路径。
在WinForms应用程序中,您可以获取exe文件的目录
string directory = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
另一个解决方案使用Reflection
string directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);