local path

G

Guest

If I start my program from a map drive, how do I get the local path or UNC
path for the application instead of the one from a map drive? I am using C#.
 
J

Jani Järvinen [MVP]

Hi Roy,
If I start my program from a map drive, how do I get the local path or UNC
path for the application instead of the one from a map drive? I am using
C#.

This is a bit tricky because at least I'm not aware of any classes/methods
in .NET class library that would do this for you. Instead, you need to call
the Win32 API function WNetGetUniversalName, but .NET's P/Invoke makes this
easy for the programmer.

Here's the definition for the said API function in C#:

-----------------
[DllImport("mpr.dll")]
public static extern int WNetGetUniversalName(
string lpLocalPath,
int dwInfoLevel,
ref StringBuilder lpBuffer,
ref int lpBufferSize);
-----------------

Then, you can write a wrapper around this function for instance like this:

-----------------
const int UNIVERSAL_NAME_INFO_LEVEL = 1;
const int ERROR_MORE_DATA = 234;

public string ConvertLocalPathToUnc(
string localPath)
{
StringBuilder buffer = new StringBuilder();
int size = 0;
int retVal = WNetGetUniversalName(
localPath, UNIVERSAL_NAME_INFO_LEVEL,
ref buffer, ref size);
if (retVal == ERROR_MORE_DATA)
{
buffer = new StringBuilder(size);
retVal = WNetGetUniversalName(
localPath, UNIVERSAL_NAME_INFO_LEVEL,
ref buffer, ref size);
if (retVal != 0)
{
throw new Win32Exception(retVal);
}
}
else
{
throw new Win32Exception(retVal);
}
return buffer.ToString();
}
-----------------

To use the method and for example get the UNC path from the mapped drive
U:\, do as follows:

-----------------
string localPath = "U:\\";
string unc = ConvertLocalPathToUnc(localPath);
MessageBox.Show(localPath + " = " + unc);
-----------------

That should do it. I also just blogged about this solution in case somebody
is looking through the answer using Google. I couldn't find a ready-made
solution to this problem with a few minutes of searching.

--
Regards,

Mr. Jani Järvinen
C# MVP
Helsinki, Finland
(e-mail address removed)
http://www.saunalahti.fi/janij/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top