Re: local path



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
janij@xxxxxxxxxxxxxxxxxxxxxx
http://www.saunalahti.fi/janij/


.



Relevant Pages

  • Re: Brian Kernighan, maybe Im not worthy, maybe Im scum
    ... conformant string. ... int repeats, reps; ... ref satisfierLength); ...
    (comp.programming)
  • Kernighan and Pikes "Beautiful" Code
    ... conformant string. ... int repeats, reps; ... ref satisfierLength); ...
    (comp.programming)
  • Re: local path
    ... public static extern int WNetGetUniversalName( ... ref StringBuilder lpBuffer, ... public string ConvertLocalPathToUnc( ... ref buffer, ref size); ...
    (microsoft.public.dotnet.framework)
  • Re: Help me!!!
    ... > private static extern int EmrDecompress_BYTE( ... > ref string pDst, ...
    (microsoft.public.dotnet.languages.csharp)
  • RE: Controling Modal Dialogs (Solution)
    ... doesn't return until the 'modal' browser returns. ... string varOptions) ... public void DocumentComplete ... int rc = winDisp.Invoke(rgDispId, ref guid, 0, ...
    (microsoft.public.inetsdk.programming.webbrowser_ctl)