gpt4 book ai didi

c# - File.Exists 可以抛出异常吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:46 24 4
gpt4 key购买 nike

根据documentation , File.Exists 方法不产生异常:

Returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

所以听起来它自己不会抛出异常。但是调用 File.Exists 会导致异常吗?换句话说,我是否需要将其包装在 try/catch 中?

最佳答案

不,根据source code :

    // Tests whether a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
public static bool Exists(string path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;

path = Path.GetFullPath(path);

// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}

return FileSystem.FileExists(path);
}
catch (ArgumentException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }

return false;
}

除非 FileSystem.FileExists 抛出一些我不知道的异常,否则似乎没有任何情况应该抛出异常。

编辑:因为我找不到FileSystem.FileExists 的源代码,所以我检查了.NET Framework source code相反,它在内部调用时有点不同:

    // Determine whether path describes an existing directory
// on disk, avoiding security checks.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static bool InternalExists(String path, out int lastError) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
lastError = File.FillAttributeInfo(path, ref data, false, true);

return (lastError == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
}

它依次调用FillAttributeInfo(代码有点长就不贴在这里了),我觉得它只会抛出IOException(在第1402行__Error.WinIOError();)

关于c# - File.Exists 可以抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57224056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com