【问题标题】:Possible to tell if a path represents a file or folder name in C#/.NET 2.0?可以判断路径是否代表 C#/.NET 2.0 中的文件或文件夹名称?
【发布时间】:2012-10-06 12:16:21
【问题描述】:

我知道过去有人问过几个类似的问题,我也知道我可以使用 Directory.Exists()File.Exists() 或使用 API 调用检查文件系统,但我试图仅根据输入做出此决定字符串。

public bool ValidateOutputFilename ( string sPath )
{
    // check if sPath is actually a filename
}

我的猜测是这是不可能的,因为看起来像文件夹名称的东西(没有扩展名但没有尾随 \)实际上可能是一个文件(例如,C:\A\B\C 可能代表一个文件或文件夹,反之亦然) .

我想避免文件系统检查的原因是因为路径可能/可能不存在,sPath 可能代表网络位置,在这种情况下文件系统查询会很慢。

我希望有人可以推荐一个我还没有考虑过的想法。

【问题讨论】:

    标签: c# .net-2.0 filenames


    【解决方案1】:

    我认为您无法避免文件系统调用。
    只有文件系统才能确定。
    正如您所说,一个简单的、格式良好的字符串是无法识别为路径或文件的。

    通过File.GetAttributes 方法可以回答您的问题。
    它返回一个FileAttributes 枚举值,可以使用按位与来测试该值是否设置了 Directory 位并且是最快的方法(除了直接的非托管调用)。

    try
    {
        // get the file attributes for file or directory 
        FileAttributes attr = File.GetAttributes(sPath);
        bool isDir = ((attr & FileAttributes.Directory) == FileAttributes.Directory) ? true : false;
        if (isDir == false)
           ....
        else
           ....
        }
    }
    catch(Exception ex)
    {
        // here as an example. probably you should handle this in the calling code
        MessageBox.Show("GetAttributes", ex.Message);
    }
    

    当然,如果路径所代表的文件或目录不存在,你会得到一个应该处理的异常。

    附带说明:Directory.Exists 或 File.Exists 可以告诉您是否存在具有指定名称的文件或目录,但是如果您不知道路径字符串代表什么,如何调用正确的名称?你需要打电话来确定。

    【讨论】:

    • 是的,你是对的,我需要两个都打电话。我没想过使用GetAttributes(),如果没有其他选择,我可能最终会使用它。
    • 另外GetAttributes() 更快
    【解决方案2】:

    除非您亲自阅读文件,否则无法获得有关文件的更多信息。据我了解,您希望避免阅读该文件。

    您别无选择,只能验证字符串中包含的扩展名和尾部斜杠。但即便如此,结果也永远不会是真实的。例如,我刚刚在我的 d 中创建了这个文件夹:

    D:\Music\file.txt
    

    我在里面创建了这个文件:

    D:\Music\file.txt\folder
    

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 2016-09-30
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2015-08-07
      相关资源
      最近更新 更多