.NET 如何检查路径是否是文件而不是目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/439447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:58:39  来源:igfitidea点击:

.NET How to check if path is a file and not a directory?

.netfiledirectory

提问by David Basarab

I have a path and I need to determine if it is a directory or file.

我有一个路径,我需要确定它是目录还是文件。

Is this the best way to determine if the path is a file?

这是确定路径是否为文件的最佳方法吗?

string file = @"C:\Test\foo.txt";

bool isFile = !System.IO.Directory.Exists(file) && 
                         System.IO.File.Exists(file);

For a directory I would reverse the logic.

对于目录,我会颠倒逻辑。

string directory = @"C:\Test";

bool isDirectory = System.IO.Directory.Exists(directory) && 
                            !System.IO.File.Exists(directory);

If both don't exists that then I won't go do either branch. So assume they both do exists.

如果两者都不存在,那么我不会去做任何一个分支。所以假设它们都存在。

回答by Alnitak

Use:

用:

System.IO.File.GetAttributes(string path)

and check whether the returned FileAttributesresult contains the value FileAttributes.Directory:

并检查返回的FileAttributes结果是否包含值FileAttributes.Directory

bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
                 == FileAttributes.Directory;

回答by Dirk Vollmar

I think this is the simplest way where you only need two checks:

我认为这是最简单的方法,您只需要进行两次检查:

string file = @"C:\tmp";
if (System.IO.Directory.Exists(file))
{
    // do stuff when file is an existing directory
}
else if (System.IO.File.Exists(file))
{
    // do stuff when file is an existing file
}

回答by Scott Dorman

You can do this with some interop code:

您可以使用一些互操作代码来做到这一点:

    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    [return: MarshalAsAttribute(UnmanagedType.Bool)]
    public static extern bool PathIsDirectory([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);

To further clarify some of the comments...

为了进一步澄清一些评论......

Introducing unmanaged code in this is not any more inherintly dangerous than any of the other file or I/O related calls in .NET since they ultimatley all call in to unmanaged code.

在此引入非托管代码并不比 .NET 中的任何其他文件或 I/O 相关调用更危险,因为它们最终都会调用非托管代码。

This is a single function call using a string. You aren't introducing any new data types and/or memory usage by calling this function. Yes, you do need to rely on the unmanaged code to properly clean up, but you ultimately have that dependency on most of the I/O related calls.

这是使用字符串的单个函数调用。通过调用此函数,您不会引入任何新的数据类型和/或内存使用。是的,您确实需要依靠非托管代码来正确清理,但您最终依赖于大多数 I/O 相关调用。

For reference, here is the code to File.GetAttributes(string path) from Reflector:

作为参考,这里是从 Reflector 到 File.GetAttributes(string path) 的代码:

public static FileAttributes GetAttributes(string path)
{
    string fullPathInternal = Path.GetFullPathInternal(path);
    new FileIOPermission(FileIOPermissionAccess.Read, new string[] { fullPathInternal }, false, false).Demand();
    Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
    int errorCode = FillAttributeInfo(fullPathInternal, ref data, false, true);
    if (errorCode != 0)
    {
        __Error.WinIOError(errorCode, fullPathInternal);
    }
    return (FileAttributes) data.fileAttributes;
}

As you can see, it is also calling in to unmanaged code in order to retrieve the file attributes, so the arguements about introducing unmanaged code being dangerous are invalid. Likewise, the argument about staying completely in managed code. There is no managed code implementation to do this. Even calling File.GetAttributes() as the other answers propose have the same "issues" of calling unmanged code and I believe this is the more reliable method to accomplish determining if a path is a directory.

如您所见,它还调用非托管代码以检索文件属性,因此关于引入非托管代码危险的论点是无效的。同样,关于完全留在托管代码中的争论。没有托管代码实现可以做到这一点。即使像其他答案一样调用 File.GetAttributes() 也存在调用非托管代码的相同“问题”,我相信这是完成确定路径是否为目录的更可靠的方法。

EditTo answer the comment by @Christian K about CAS. I believe the only reason GetAttributes makes the security demand is because it needs to read the properties of the file so it wants to make sure the calling code has permission to do so. This is not the same as the underlying OS checks (if there are any). You can always create a wrapper function around the P/Invoke call to PathIsDirectory that also demands certain CAS permissions, if necessary.

编辑回答@Christian K 关于 CAS 的评论。我相信 GetAttributes 提出安全要求的唯一原因是因为它需要读取文件的属性,因此它希望确保调用代码具有这样做的权限。这与底层操作系统检查(如果有)不同。如有必要,您始终可以围绕对 PathIsDirectory 的 P/Invoke 调用创建包装函数,该函数也需要某些 CAS 权限。

回答by tvanfosson

Assuming the directory exists...

假设目录存在...

bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
                  == FileAttributes.Directory;

回答by Dror

Check this out:

看一下这个:

/// <summary>
/// Returns true if the given file path is a folder.
/// </summary>
/// <param name="Path">File path</param>
/// <returns>True if a folder</returns>
public bool IsFolder(string path)
{
    return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}

from http://www.jonasjohn.de/snippets/csharp/is-folder.htm

来自http://www.jonasjohn.de/snippets/csharp/is-folder.htm

回答by Igor Zelaya

Read the file attributes:

读取文件属性:

FileAttributes att = System.IO.File.GetAttributes(PATH_TO_FILE);

Check for the Directoryflag.

检查目录标志。

回答by Drew Noakes

Given that a particular path string cannot represent both a directory anda file, then the following works just fine and opens the door for other operations.

鉴于特定的路径字符串不能同时表示目录文件,那么下面的工作就好了,并为其他操作打开了大门。

bool isFile = new FileInfo(path).Exists;
bool isDir = new DirectoryInfo(path).Exists;

If you're working with the file system, using FileInfoand DirectoryInfois much simpler than using strings.

如果您正在使用文件系统,使用FileInfoDirectoryInfo比使用字符串简单得多。

回答by Onikoroshi

Hmm, it looks like the Filesclass (in java.nio) actually has a static isDirectorymethod. So, I think you could actually use the following:

嗯,看起来Files类 (in java.nio) 实际上有一个静态isDirectory方法。所以,我认为你实际上可以使用以下内容:

Path what = ...
boolean isDir = Files.isDirectory(what);