[英]Checking the existence of a file using relative path
使用相对路径检查文件是否存在的最佳方法是什么。
我使用了以下方法,但尽管文件存在,但它返回 false。
bool a = File.Exists("/images/Customswipe_a.png");
那不是相对路径。 你需要去掉第一个/
否则它会被解释为 root (即 C:/images...)
我猜您是在 asp.net 应用程序中运行此代码,这就是您得到错误的原因。
在 asp.net 中,您应该使用Server.MapPath("/images/Customswipe_a.png")
来获取“正确”路径(相对于 Web 应用程序根目录)。 否则,您将获得网络服务器可执行文件的本地路径(IIS/WEBDAV/..name 任何其他)。
相对路径是相对于当前工作目录的。 它可能不是应用程序目录。 调用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
通常是一个错误的决定。
您可以使用 System.IO.DirectoryInfo 测试此路径:
DirectoryInfo info = new DirectoryInfo("/images/Customswipe_a.png");
string absoluteFullPath = info.FullName;
由于 Mike Park 正确回答了这条路径很可能是(即 C:/images...)
相对路径,是一个相对的东西。 在这个 API 中,它会根据文档File.Exists :
相对路径信息被解释为相对于当前工作目录。
所以这里的一切都取决于执行此查询时CurrentDirectoty是什么。
另外,您的路径不是有效的桌面路径(我假设您是从某个 Web 文件或知识中选择的)。 要了解指定的路径是否包含无效字符,请使用GetInvalidCharacters函数。
在您的特定情况下,使用@"\\images\\Customswipe_a.png"
就足够了。
该路径相对于二进制文件的位置。 对于 Visual Studio 项目,这将是%PROJECTDIR%/bin/(RELEASE||DEBUG)/
我要做的是将文件系统根目录放在一个配置文件中,并将其用于您的相对路径。
在 WinForms 应用程序中,您可以使用以下命令获取 exe 文件的目录
string directory =
Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
另一种解决方案使用反射
string directory =
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
从.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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.