确定文件是否存在使用C#和解决UNC路径 [英] Determining if file exists using c# and resolving UNC path
问题描述
我试图写一个函数来确定文件是否存在。这两种方法证明返回不一致的结果(FILEEXISTS()似乎提供准确的结果,相比isFileFound()返回误报 - 我本来期望试图创建实例时除外)。
I am trying to write a function to determine if a file exists. The two methods prove to return inconsistent results (fileExists() seems to provide accurate results, compared to isFileFound(), that returns false positives - i would have expected an exception when trying to create the instance).
protected bool isFileFound(string path, string fileName)
{
System.IO.FileInfo fi = null;
bool found = false;
try
{
fi = new System.IO.FileInfo(path + fileName);
found = true;
}
catch (Exception e)
{
baselogger.Fatal(e.Message + " " + e.StackTrace + " \n" + path + fileName);
}
return found;
}
protected bool fileExists(string path, string pattern)
{
bool success = false;
try
{
success = File.Exists(path + pattern);
}
catch (Exception e)
{
baselogger.Warn(e.Message + " " + e.StackTrace + " " + e.Source);
}
return success;
}
似乎都不是能够解决以下语法的UNC路径: \\\\ abcserver \\ C $ \\ xyzfolder \\ foo.bar 的
Neither seems to be able to resolve a UNC path of the following syntax: \\abcserver\c$\xyzfolder\foo.bar
任何想法,为什么UNC路径是失败了这些方法将大大AP preciated。
Any idea why the unc path is failing for these methods would be greatly appreciated.
推荐答案
您可以为不存在的文件中创建一个FileInfo。不过,你可以检查FileInfo.Exists属性来确定文件是否存在,例如:
You can create a FileInfo for an non-existing file. But then you can check the FileInfo.Exists property to determine whether the file exists, e.g:
FileInfo fi = new FileInfo(somePath);
bool exists = fi.Exists;
更新:
在很短的测试,这也工作了UNC路径,例如像这样的:
Update: In a short test this also worked for UNC paths, e.g. like this:
FileInfo fi = new FileInfo(@"\\server\share\file.txt");
bool exists = fi.Exists;
您确定该帐户(下运行应用程序)的访问共享。我认为,(默认)的管理权限需要访问该共享的C $。
Are you sure that the account (under which your application is running) has access to the share. I think that (by default) administrative rights are required to access the share "c$".
这篇关于确定文件是否存在使用C#和解决UNC路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!