My software handles multiple operations on files, and I have now finished writing the related functions, using the System.IO classes.
I now need to add support for network drives. Using a mapping works very well (although Directory.GetFiles is a bit low, and I don’t know why), but I’d now like to be able to deal directly with paths such as \\192.168.0.10\Shared Folder\MyDrive. Is there any way to handle this type of paths other than mounting the drive to an available drive letter, using the newly generated path, and then unmounting?
You can use the UNC path (which starts with
\\) directly in your paths. However, you must account for the credentials for this connection, which can be the tricky part.There are several approaches:
If the remote system is on the same domain or there is a trust relationship between the domains, and the user your program is running as has suitable access, it will “just work”.
You can shell out and execute the
net usecommand (through the Windowsnet.exeprogram) to make a connection with a specific username and password. Be aware that connection is usable by any program running in the user’s session, not just your application. Use the/DELETEcommand to remove the connection when you are done. The typical syntax is:net use \\computername\sharename password /USER:domain\username.You can P/Invoke
WNetAddConnection2to accomplish the same thing asnet usewithout shelling out tonet.exe. By passing NULL aslpLocalName, no drive letter is assigned, but the username and password will apply to subsequent accesses made through the UNC path. TheWNetCancelConnection2function can be used to disconnect.You can P/Invoke
LogonUserwith theLOGON32_LOGON_NEW_CREDENTIALSflag followed by an impersonation to add additional remote credentials to your thread. Unlike #2 and #3, the effects on the user’s entire session will be a little more limited. (In practice, this is rarely done in favor of the well-knownWNetAddConnection2solution.)The following is a sample of how to call
WNetAddConnection2from VB.NET.