getting network computer name

  • Thread starter Thread starter wheels619
  • Start date Start date
W

wheels619

Hi,
I know that System.Windows.Forms.SystemInformation.ComputerName
retrieves the current computer's name, but is it possible to fetch the
computer's name from a file path?

ie. G:\file.txt exists on the computer named Tool, how I can get the
name Tool?

Thanks.
Tommy
 
I think you will need to use P/Invoke on WNetGetUniversalName. From
this you can get the UNC path like \\machinename\sharename. This code
worked for me:

[DllImport("mpr.dll")]
[return: MarshalAs(UnmanagedType.U4)]
static extern int WNetGetUniversalName(
string lpLocalPath,
[MarshalAs(UnmanagedType.U4)] int dwInfoLevel,
IntPtr lpBuffer,
[MarshalAs(UnmanagedType.U4)] ref int lpBufferSize);

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode),
Serializable()]
class MyUNC
{
[MarshalAs(UnmanagedType.LPStr)]
public string UniversalName;
[MarshalAs(UnmanagedType.LPStr)]
public string ConnectionName;
[MarshalAs(UnmanagedType.LPStr)]
public string RemainingPath;
}
[STAThread]
static void Main()
{
int bufferSize = 2000;
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
int ret = WNetGetUniversalName("P:", 2, buffer, ref bufferSize);
if (ret == 0)
{
MyUNC unc = new MyUNC();
Marshal.PtrToStructure(buffer, unc);
Console.WriteLine(unc.UniversalName);
}
Marshal.FreeHGlobal(buffer);
return;
}

John
 

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

Back
Top