Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,44 +26,37 @@ internal static int GetUNCForNetworkDrive(char drive, out string? uncPath)

uint bufferSize = MAX_PATH;

#if DEBUG
// In Debug mode buffer size is initially set to 3 and if additional buffer is required, the
// required buffer size is allocated and the WNetGetConnection API is executed with the newly
// allocated buffer size.
bufferSize = 3;
#endif

ReadOnlySpan<char> driveName = stackalloc char[] { drive, ':', '\0' };
Span<char> uncBuffer = stackalloc char[(int)bufferSize];
int errorCode = ERROR_NO_NETWORK;

try
{
errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize);
}
catch (System.DllNotFoundException)
char[]? rentedArray = null;
while (true)
{
s_WNetApiNotAvailable = true;
return ERROR_NOT_SUPPORTED;
}

if (errorCode == ERROR_SUCCESS)
{
// exclude null terminator
uncPath = uncBuffer.Slice(0, (int)bufferSize - 1).ToString();
}
else if (errorCode == ERROR_MORE_DATA)
{
char[]? rentedArray = null;
int errorCode;
try
{
uncBuffer = rentedArray = ArrayPool<char>.Shared.Rent((int)bufferSize);
errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize);
try
{
errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize);
}
catch (System.DllNotFoundException)
{
s_WNetApiNotAvailable = true;
return ERROR_NOT_SUPPORTED;
}

if (errorCode == ERROR_SUCCESS)
{
// exclude null terminator
uncPath = uncBuffer.Slice(0, (int)bufferSize - 1).ToString();
// Cannot rely on bufferSize as it's only set if
// the first call ended with ERROR_MORE_DATA,
// instead slice at the null terminator.
unsafe
{
fixed (char* uncBufferPtr = uncBuffer)
{
uncPath = new string(uncBufferPtr);
}
}
}
}
finally
Expand All @@ -73,9 +66,16 @@ internal static int GetUNCForNetworkDrive(char drive, out string? uncPath)
ArrayPool<char>.Shared.Return(rentedArray);
}
}
}

return errorCode;
if (errorCode == ERROR_MORE_DATA)
{
uncBuffer = rentedArray = ArrayPool<char>.Shared.Rent((int)bufferSize);
}
else
{
return errorCode;
}
}
}
}
}