Re: local path
- From: Roy <Roy@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 15 Jan 2007 07:12:00 -0800
I pass in a directory of the map drive such as "Z:\Mydirectory" where "Z:" is
a map drive on my local system such as "C:\MyShare"
It always return me an error with
"This network connection does not exist"
What's wrong with it? I am sure the map drive exist.
"Jani Järvinen [MVP]" wrote:
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/
- References:
- Re: local path
- From: Jani Järvinen [MVP]
- Re: local path
- Prev by Date: DotNet 1.1 - C# - TabControl;TabPage;CheckedListBox
- Next by Date: Re: Policy File Not Working?
- Previous by thread: Re: local path
- Next by thread: Re: Valid constraints.
- Index(es):
Relevant Pages
|