c# - 使用 C# 确定文件是否存在并解析 UNC 路径

标签 c# filesystems

我正在尝试编写一个函数来确定文件是否存在。这两种方法证明会返回不一致的结果(与返回误报的 isFileFound() 相比,fileExists() 似乎提供了准确的结果——我本以为在尝试创建实例时会出现异常)。

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

如果知道这些方法的 unc 路径失败的原因,我们将不胜感激。

最佳答案

您可以为不存在的文件创建一个 FileInfo。但是随后您可以检查 FileInfo.Exists 属性以确定文件是否存在,例如:

FileInfo fi = new FileInfo(somePath);
bool exists = fi.Exists;

更新: 在一个简短的测试中,这也适用于 UNC 路径,例如像这样:

FileInfo fi = new FileInfo(@"\\server\share\file.txt");
bool exists = fi.Exists;

您确定帐户(您的应用程序在其下运行)可以访问该共享。我认为(默认情况下)需要管理权限才能访问共享“c$”。

关于c# - 使用 C# 确定文件是否存在并解析 UNC 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/458363/

相关文章:

c# - String.replace 删除反斜杠

c# - 求请求时传入回调url

database - Base64 编码数据 - 数据库或文件系统

filesystems - 为 linux、mac、windows 开发 "File Systems"

c++ - 来自 ExpandEnvironmentStrings 的本地化值

C#读写给定缓冲区长度的文件并剪切溢出

c# - 使用 System.Data.OracleClient 配置 Fluent NHibernate

javascript - Electron 从具有偏移量和长度的路径读取文件

node.js - 在 Windows 上完美运行的 Node JS FS 代码在 Ubuntu 服务器中不起作用

c# - ASP.NET MVC Core 3.0 - 为什么来自主体的 API 请求不断返回!ModelState.IsValid?