如何使用相对路径检查文件是否存在是最好的方式。
我使用了以下方法,但尽管文件存在,它仍返回false。
bool a = File.Exists("/images/Customswipe_a.png");
如何使用相对路径检查文件是否存在是最好的方式。
我使用了以下方法,但尽管文件存在,它仍返回false。
bool a = File.Exists("/images/Customswipe_a.png");
那不是相对路径。 你需要省略第一个 /
,否则它将被解释为根目录(例如C:/images...)。
Path.IsPathRooted
不同,这是另一种看待它的方式)。我很难将路径“\p\f.txt”称为绝对路径,因为它可以引用“c:\p\f.txt”或“d:\p\f.txt”,具体取决于当前路径... “c:\path\file.txt”或“\server\path\file.txt”在我看来更加绝对。 - Alexei Levenkov我猜你正在运行asp.net应用程序,这就是为什么你得到了false的原因。
在asp.net中,您应该使用Server.MapPath("/images/Customswipe_a.png")
来获取“正确”的路径(相对于Web应用程序根目录)。否则,您会得到相对于Web服务器可执行文件(IIS / WEBDAV / ..name any other)的路径。
相对路径是相对于当前工作目录的。它可能不是应用程序目录。调用 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
通常是错误的决定。
您可以使用System.IO.DirectoryInfo测试此路径:
DirectoryInfo info = new DirectoryInfo("/images/Customswipe_a.png");
string absoluteFullPath = info.FullName;
相对路径是相对于某个东西的相对路径。 在这个API中,根据文档File.Exists的说明:
相对路径信息被解释为相对于当前工作目录。
所以这里的一切都取决于执行此查询时的CurrentDirectoty是什么。
另外,您的路径不是有效的桌面路径(我假设您从某个Web文件或知识中选择它)。要了解指定的路径是否包含无效字符,请使用GetInvalidCharacters函数。
在您的特定情况下,只需使用@"\images\Customswipe_a.png"
即可。
Path.GetInvalidPathChars().Contains('/')
不会将“/”报告为无效... - Alexei Levenkov从.NET Core 3.1开始,这个功能可以使用:
使用依赖注入来包含服务IWebHostEnvironment
private IWebHostEnvironment Env;
public MyController (IWebHostEnvironment env){
Env = env;
}
然后使用Env.ContentRootPath
来获取应用程序根路径
最后合并所有内容:
var file = System.IO.Path.Combine(Env.ContentRootPath, "images", "some-file.png");
string directory =
Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
另一种解决方案使用反射
string directory =
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
路径是相对于二进制文件的位置而言的。在Visual Studio项目中,这将是%PROJECTDIR%/bin/(RELEASE||DEBUG)/
我会把文件系统根目录放在配置文件中,并使用它来设置相对路径。
/
而不是\\
? - Claudio Redi