user1556023
user1556023

Reputation: 71

UNC conversion using Visual Studio 2010

I am writing a document indexing system that will reference 100’s of files across a computer network with many computer drives. When new drives are added or drives are removed from the network, the drive letters are re-assigned. Hence any particular file path using a drive letter may become meaningless if its drive letter is re-assigned. In order to avoid this problem I want to use the UNC (Universal naming convention) path name instead.

The code shown below will convert a drive letter to its UNC equivalent when run in Excel 2007. However my application is written in Visual Studio 2010, unfortunately the code below doesn’t seem to work in Visual Studio. No errors are reported when it runs, but it doesn’t return the UNC. It may be a problem with a ‘Reference’ that that needs set.

Imports System
Imports System.Management
Module Module1

' 32-bit Function version.
' Enter this declaration on a single line.
Declare Function WNetGetConnection Lib "MPR.DLL" Alias _
   "WNetGetConnectionA" (ByVal lpszLocalName As String, ByVal _
   lpszRemoteName As String, ByVal lSize As Long) As Long

Dim lpszRemoteName As String
Dim lSize As Long

' Use for the return value of WNetGetConnection() API.
Const NO_ERROR As Long = 0

' The size used for the string buffer. Adjust this if you
' need a larger buffer.
Const lBUFFER_SIZE As Long = 255


Sub GetNetPath()
    Dim DriveLetter, lpszLocalName As String
    Dim cbRemoteName As Long
    Dim lStatus&


    ' Prompt the user to type the mapped drive letter.
    DriveLetter = UCase(InputBox("Enter Drive Letter of Your Network" & _
       "Connection." & Chr(10) & "i.e. F (do not enter a colon)"))

    ' Add a colon to the drive letter entered.
    lpszLocalName = DriveLetter & ":"

    ' Specifies the size in characters of the buffer.


    ' Prepare a string variable by padding spaces.
    lpszRemoteName = lpszRemoteName & Space(lBUFFER_SIZE)
    cbRemoteName = Len(lpszRemoteName)
    ' Return the UNC path (\\Server\Share).
    lStatus& = WNetGetConnection(lpszLocalName, lpszRemoteName, _
       cbRemoteName)

    ' Verify that the WNetGetConnection() succeeded. WNetGetConnection()
    ' returns 0 (NO_ERROR) if it successfully retrieves the UNC path.
    If lStatus& = NO_ERROR Then

        ' Display the UNC path.
        MsgBox(Left$(lpszRemoteName, cbRemoteName))

    Else
        ' Unable to obtain the UNC path.
        MsgBox("Unable to obtain the UNC path.")
    End If

End Sub


End Module

Any suggestions gratefully received. Thanks very much

Upvotes: 1

Views: 613

Answers (1)

Praveen
Praveen

Reputation: 100

One way is string strUncpath="file:\"; thenjust prepend this to your path

strUncpath+ what ever is your path or you can create an extension method out of this, prepending file:\ to yoi

Upvotes: 0

Related Questions