MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4#nullable enable5 6using System;7using System.Buffers;8using System.Runtime.InteropServices;9using System.Management.Automation.Internal;10 11internal static partial class Interop12{13 internal static unsafe partial class Windows14 {15 private static bool s_WNetApiNotAvailable;16 17 [LibraryImport("mpr.dll", EntryPoint = "WNetGetConnectionW", StringMarshalling = StringMarshalling.Utf16)]18 internal static partial int WNetGetConnection(ReadOnlySpan<char> localName, Span<char> remoteName, ref int remoteNameLength);19 20 internal static int GetUNCForNetworkDrive(char drive, out string? uncPath)21 {22 uncPath = null;23 if (s_WNetApiNotAvailable)24 {25 return ERROR_NOT_SUPPORTED;26 }27 28 ReadOnlySpan<char> driveName = [drive, ':', '\0'];29 int bufferSize = MAX_PATH;30 Span<char> uncBuffer = stackalloc char[MAX_PATH];31 if (InternalTestHooks.WNetGetConnectionBufferSize > 0 && InternalTestHooks.WNetGetConnectionBufferSize <= MAX_PATH)32 {33 bufferSize = InternalTestHooks.WNetGetConnectionBufferSize;34 uncBuffer = uncBuffer.Slice(0, bufferSize);35 }36 37 char[]? rentedArray = null;38 while (true)39 {40 int errorCode;41 try42 {43 try44 {45 errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize);46 }47 catch (DllNotFoundException)48 {49 s_WNetApiNotAvailable = true;50 return ERROR_NOT_SUPPORTED;51 }52 53 if (errorCode == ERROR_SUCCESS)54 {55 // Cannot rely on bufferSize as it's only set if56 // the first call ended with ERROR_MORE_DATA,57 // instead slice at the null terminator.58 unsafe59 {60 fixed (char* uncBufferPtr = uncBuffer)61 {62 uncPath = new string(uncBufferPtr);63 }64 }65 }66 }67 finally68 {69 if (rentedArray is not null)70 {71 ArrayPool<char>.Shared.Return(rentedArray);72 }73 }74 75 if (errorCode == ERROR_MORE_DATA)76 {77 uncBuffer = rentedArray = ArrayPool<char>.Shared.Rent(bufferSize);78 }79 else80 {81 return errorCode;82 }83 }84 }85 }86}87 