简体   繁体   中英

Adding network drives in C# as admin: disappear after logoff

Ok, first of all: my task is, to map a network drive programmatically from a C# program that runs as administrator .

I managed to map a drive as my normal admin user without elevated privileges and it was still visible after logoff/reboot (even though it didn't reconnect, but that's a different story). I did this with the WNetAddConnection2 WinApi function and also with the net use command in cmd, just to check.

Sadly, both didn't work with elevated privileges. In this case the drive is added as it schould, but after a reboot it is completely gone.

Is it even possible to achieve this with elevated privileges or is there some Windows account magical stuff I don't know about that prevents that?

Here is the Code I used, setting all flags that should usually make the drive be remembered and also reconnected:

uint flags = (uint)(Flags.CONNECT_CMD_SAVECRED | 
                    Flags.CONNECT_INTERACTIVE | 
                    Flags.CONNECT_COMMANDLINE | 
                    Flags.CONNECT_UPDATE_PROFILE);

NETRESOURCE NetworkResource = new NETRESOURCE();
oNetworkResource.dwType = ResourceType.RESOURCETYPE_DISK;
oNetworkResource.lpLocalName = Console.ReadLine() + ":";
oNetworkResource.lpRemoteName = @"\\[Server]\foo";
oNetworkResource.lpProvider = null;

Console.WriteLine(WNetAddConnection2(NetworkResource, "[Password]", @"[Domain]\[Username]", flags));

it was still visible after logoff/reboot

this is because, when CONNECT_UPDATE_PROFILE flag used - called exported, but undocumented function I_MprSaveConn (from mpr.dll ) which save in registry, under HKEY_CURRENT_USER\\Network\\<lpLocalName> information which you pass to WNetAddConnection2 . but I_MprSaveConn at very begin call function bool IsElevatedCaller(PLUID ) and if function return true - it just exit, without saving in registry. so you absolute correct - when you call WNetAddConnection2 from elevated process ( without impersonation ) - this connection not persist (info not saved in registry)

solution: you need got not elevated token (say from explorer ) - open/duplicate (for TokenImpersonation type) and call SetThreadToken . in this case IsElevatedCaller ( can ) return false (it first try open thread token (only if it not exist - process token) ) and query opened token for TokenElevationType (and return true if TokenElevationTypeFull )

so this of course not documented, but current (i test) if you impersonate self thread with not elevated token (how you got it separate question) flag CONNECT_UPDATE_PROFILE will be worked well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM