views:

504

answers:

6

How do I determine a mapped drive's actual path?

So if I have a mapped drive on a machine called "Z" how can I using .NET determine the machine and path for the mapped folder?

The code can assume it's running on the machine with the mapped drive.

I looked at Path, Directory, FileInfo objects, but can't seem to find anything.

I also looked for existing questions, but could not find what I'm looking for.

+1  A: 

Here are some code samples:

mjmarsh
I have confirmed the C# code from the link works. I would rather have a non-dll import version, but better than nothing at all.
eschneider
+1  A: 

Seems it's need a P/Invoke: Converting a mapped drive letter to a network path using C#

This guy built a managed class to deal with it: C# Map Network Drive (API)

Rubens Farias
Looks like this allows you to map or un-map drives via code, I don't see anything on obtaining a path from a mapped path.
eschneider
+1  A: 

QueryDosDevice translates a drive letter into the path that it expands to.

Note that this will translate ALL drive letters, not just those that are mapped to network connections. You need to already know which are network paths, or to parse the output to see which are network.

Here's the VB signature

Declare Function QueryDosDevice Lib "kernel32" Alias "QueryDosDeviceA" (
       ByVal lpDeviceName    As String, 
       ByVal lpTargetPath As String, 
       ByVal ucchMax As Integer) As Integer 

And the C# one

[DllImport("kernel32.dll")]
static extern uint QueryDosDevice(string lpDeviceName, IntPtr lpTargetPath, uint ucchMax);
John Knoeller
I can't get this to work, also this look like it will not give the folder, mapped driver are to a server and a folder...
eschneider
If you mean you want to know that path as it appears to the server, then you will need to ask the server. That information isn't available to the client.
John Knoeller
If the drive is mapped on the machine the code is running on then it should work.
eschneider
You will get back \\server\share on the machine that the drive is mapped on. The server may have share aliased to c:\foo\bar\whatever, If you want that then you have to ask the server.
John Knoeller
A: 

As far as Windows cares, what's needed is a call to WNetGetConnection. I don't know of a front-end for that in .NET, so you may have to call it via P/Invoke (fortunately, it has only one parameter, the P/Invoke code isn't too awful).

Jerry Coffin
+1  A: 

You can also use WMI Win32_LogicalDisk to get all the information you need. use the ProviderName from the class to get the UNC path.

rerun
A: 

You can use WMI to interrogate the Win32_LogicalDrive collection on your machine. Here is an example of how to do it with scripting. Changing this over to C# is pretty well explained in other places.

Nick