Skip to content

Commit

Permalink
Reduce Kernel32 calls
Browse files Browse the repository at this point in the history
  • Loading branch information
deeprobin committed Mar 16, 2022
1 parent f0b7773 commit 8ce1a96
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ public static bool FileExists(string fullPath)
((data.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0);
}

public static (int fileAttributes, int lastError) GetFileAttributes(string fullPath)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int lastError = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true);
int fileAttributes = data.dwFileAttributes;

return (fileAttributes, lastError);
}

/// <summary>
/// Returns 0 on success, otherwise a Win32 error code. Note that
/// classes should use -1 as the uninitialized state for dataInitialized.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,16 @@ public static unsafe void CreateDirectory(string fullPath, byte[]? securityDescr
}
else
{
(int fileAttributes, int lastError) = GetFileAttributes(name);
currentError = lastError;

int directoryAttributeValue = fileAttributes &
Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY;
bool fileExists = lastError == Interop.Errors.ERROR_SUCCESS && directoryAttributeValue != 0;
bool directoryExists = directoryAttributeValue == 0;

// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
if (FileExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.Errors.ERROR_ACCESS_DENIED))
if (fileExists || !directoryExists && currentError == Interop.Errors.ERROR_ACCESS_DENIED)
{
firstError = currentError;
errorString = name;
Expand Down

0 comments on commit 8ce1a96

Please sign in to comment.