Author Topic: Convert pathname to UNC path  (Read 3876 times)

0 Members and 1 Guest are viewing this topic.

mkweaver

  • Bull Frog
  • Posts: 344
Convert pathname to UNC path
« on: November 16, 2007, 08:03:53 AM »
Using vb.net (visual studio 2005) how would I convert a fully qualified pathname to a UNC path?  I have found lots of examples on line that will do this using API calls, and I know it can be done with scripting, but I thought .net would provide an easier way.

Mike

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Convert pathname to UNC path
« Reply #1 on: November 16, 2007, 10:48:48 PM »
This may get you started Mike
.. uses WNetGetConnection

You'll just need to strip the Drive from your Qualified Path
and test the Drive with  WNetGetConnection
and add the trailing Path to the ServerName returned.

Code: [Select]
using System;

using System.IO; // Directory
using System.Text; // StringBuilder
using System.Runtime.InteropServices; // DllImport

/*
References :
System.dll
*/
//----------------------------------------------
// kwb: 2007/11/17 13:41:02
//----------------------------------------------

namespace GetUNCPath
{
    class Program
    {
        #region API functions / calls
        //======================================================================================
        // Use DllImport to import the Win32 MessageBox function.
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int MessageBox(
            IntPtr hWnd,
            String text,
            String caption,
            uint type);

        [DllImport("kernel32.dll")]
        static extern uint QueryDosDevice(
            string lpDeviceName,
            StringBuilder lpTargetPath,
            int ucchMax );

        [DllImport("mpr.dll", EntryPoint = "WNetGetConnection", SetLastError = true)]
        public static extern int WNetGetConnection(
            string strLocalName,
            StringBuilder strbldRemoteName,
            ref int intRemoteNameLength); // <--- Note ref

        //======================================================================================
        #endregion

        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
                Console.WriteLine("UserName: {0}", Environment.UserName);
                Console.WriteLine("MachineName: {0}", Environment.MachineName);
                Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
                //               
                string[] drives = Directory.GetLogicalDrives();
                Console.WriteLine("Directory.GetLogicalDrives(): {0}", String.Join(", ", drives));
                //
                for (int i = 0; i < drives.Length; i++)
                    Console.WriteLine("RealPath :{0} -> {1}",
                        (drives[i]),
                        (GetRealPath(drives[i])));

                //------------------------------------------------------------------------------------
 
                StringBuilder strbldRemoteName = new StringBuilder();
                int intRemoteNameLength = 100; // <--- Note Set the max. number of char
                strbldRemoteName.Capacity = intRemoteNameLength;

                Console.Write(@"Enter Drive: ");
                string strDrive = Console.ReadLine();

                // status = 0 (No Error)
                int status = WNetGetConnection(
                                            strDrive,
                                            strbldRemoteName,
                                            ref intRemoteNameLength);
                Console.WriteLine("UNC Path :{0} -> {1}", strDrive, strbldRemoteName.ToString());
                MessageBox(new IntPtr(0), strbldRemoteName.ToString(), "TheSwampRules OK", 0);

                Console.Read();
            }
            catch (IOException e) { Console.WriteLine(e.ToString()); }
        }
        //======================================================================================
        //
        // Modified code from http://www.pinvoke.net/default.aspx/kernel32.QueryDosDevice
        //
        private static string GetRealPath(string path)
        {
            string realPath;
            StringBuilder pathInformation = new StringBuilder(250);

            // Get the drive letter of the
            string driveLetter = Path.GetPathRoot(path).Replace("\\", "");
            QueryDosDevice(driveLetter, pathInformation, 250);

            // If drive is substed, the result will be in the format of "\??\C:\RealPath\".
            if (pathInformation.ToString().Contains("\\??\\"))
            {
                // Strip the \??\ prefix.
                string realRoot = pathInformation.ToString().Remove(0, 4);

                //Combine the paths.
                realPath = Path.Combine(realRoot, path.Replace(Path.GetPathRoot(path), ""));
            }
            else
            {
                realPath = path;
            }
            return realPath;
        }
        //======================================================================================

        //======================================================================================

        //======================================================================================
    }
}


And the obligatory piccy ..
« Last Edit: November 18, 2007, 05:02:59 AM by Kerry Brown »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Convert pathname to UNC path
« Reply #2 on: November 17, 2007, 12:18:43 AM »
afterthoughts
I can't post VB.net [ instruction from therapist ]
There are no native methods as far as I know.
Posted this for anyone else interested in C#.
I'll add the remainder for the string twiddling when my head cools down.

Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

mkweaver

  • Bull Frog
  • Posts: 344
Re: Convert pathname to UNC path
« Reply #3 on: November 17, 2007, 10:34:10 AM »
C#.  Now that will make my head hurt, but I'll take a shot at it.

Thanks

Nathan Taylor

  • Guest
Re: Convert pathname to UNC path
« Reply #4 on: November 18, 2007, 04:59:39 PM »
C#.  Now that will make my head hurt, but I'll take a shot at it.

Thanks

Converted ot VB using http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx

Code: [Select]
Imports System

Imports System.IO
' Directory
Imports System.Text
' StringBuilder
Imports System.Runtime.InteropServices
' DllImport
'
'References :
'System.dll
'

'----------------------------------------------
' kwb: 2007/11/17 13:41:02
'----------------------------------------------

Namespace GetUNCPath
    Class Program
        #Region "API functions / calls"
        '======================================================================================
        ' Use DllImport to import the Win32 MessageBox function.
        <DllImport("user32.dll", CharSet := CharSet.Auto)> _
        Public Shared Function MessageBox(ByVal hWnd As IntPtr, ByVal text As String, ByVal caption As String, ByVal type As UInteger) As Integer
        End Function
       
        <DllImport("kernel32.dll")> _
        Private Shared Function QueryDosDevice(ByVal lpDeviceName As String, ByVal lpTargetPath As StringBuilder, ByVal ucchMax As Integer) As UInteger
        End Function
       
        <DllImport("mpr.dll", EntryPoint := "WNetGetConnection", SetLastError := True)> _
        Public Shared Function WNetGetConnection(ByVal strLocalName As String, ByVal strbldRemoteName As StringBuilder, ByRef intRemoteNameLength As Integer) As Integer
        End Function
        ' <--- Note ref
        '======================================================================================
        #End Region
       
        Private Shared Sub Main(ByVal args As String())
            Try
                Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory)
                Console.WriteLine("UserName: {0}", Environment.UserName)
                Console.WriteLine("MachineName: {0}", Environment.MachineName)
                Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName)
                '
                Dim drives As String() = Directory.GetLogicalDrives()
                Console.WriteLine("Directory.GetLogicalDrives(): {0}", [String].Join(", ", drives))
                For i As Integer = 0 To drives.Length - 1
                    Console.WriteLine("RealPath :{0} -> {1}", (drives(i)), (GetRealPath(drives(i))))
                Next
                '
               
                '------------------------------------------------------------------------------------
               
                Dim strbldRemoteName As New StringBuilder()
                Dim intRemoteNameLength As Integer = 100
                ' <--- Note Set the max. number of char
                strbldRemoteName.Capacity = intRemoteNameLength
               
                Console.Write("Enter Drive: ")
                Dim strDrive As String = Console.ReadLine()
               
                ' status = 0 (No Error)
                Dim status As Integer = WNetGetConnection(strDrive, strbldRemoteName, intRemoteNameLength)
                Console.WriteLine("UNC Path :{0} -> {1}", strDrive, strbldRemoteName.ToString())
                MessageBox(New IntPtr(0), strbldRemoteName.ToString(), "TheSwampRules OK", 0)
               
                Console.Read()
            Catch e As IOException
                Console.WriteLine(e.ToString())
            End Try
        End Sub
        '======================================================================================
        '
        ' Modified code from http://www.pinvoke.net/default.aspx/kernel32.QueryDosDevice
        '
        Private Shared Function GetRealPath(ByVal path As String) As String
            Dim realPath As String
            Dim pathInformation As New StringBuilder(250)
           
            ' Get the drive letter of the
            Dim driveLetter As String = Path.GetPathRoot(path).Replace("\", "")
            QueryDosDevice(driveLetter, pathInformation, 250)
           
            ' If drive is substed, the result will be in the format of "\??\C:\RealPath\".
            If pathInformation.ToString().Contains("\??\") Then
                ' Strip the \??\ prefix.
                Dim realRoot As String = pathInformation.ToString().Remove(0, 4)
               
                'Combine the paths.
                realPath = Path.Combine(realRoot, path.Replace(Path.GetPathRoot(path), ""))
            Else
                realPath = path
            End If
            Return realPath
        End Function
        '======================================================================================
       
        '======================================================================================
       
        '======================================================================================
    End Class
End Namespace