Wednesday, June 27, 2018

Grabbing UNC path from a Mapped Drive

I am among those who stores only the fullpath() of the outside files into a field as I do not want to store the actual files inside the tables as that will make the tables huge as time goes by.

I am also not an admirer of a mapped drive as that will lead to a lot of problems later such as giving users easy access to the folder for the app, issue of sleeping mapped drives, or workstations using different mapped drive letters.

Anyway, this is so in case you have mapped drives in your workstations and you want to get a fullpath() of a file using GETFILE(), then you can always get the UNC path if file is coming from a network drive.  For instance, if you have a mapped drive Z:\ and you point to a file there, instead of getting Z:\myFile.jpg you will get \\192.168.1.1\YourFolder\myFile.jpg or something like that instead; where drive Z: will be replaced by the actual UNC path.

Here is a code for that:


Local lcFile
lcFile = GETUNC(Getfile())
Messagebox(m.lcFile)

********
Function GETUNC(cFile)
********
Local lcFullPath, lcDrive, lcUNC, lnSize
If !Empty(m.cFile)
      lcDrive = Justdrive(m.cFile)
      lcFullPath = Fullpath(m.cFile)
      If Drivetype(m.lcDrive) = 4
            lnSize = 600
            lcUNC = Space(lnSize)
            Declare Integer WNetGetConnection In WIN32API String @lcDrive, String @lcUNC, Integer @lnSize
            WNetGetConnection(@lcDrive, @lcUNC, @lnSize)
            lcFullPath = Strtran(m.lcFullPath,m.lcDrive,Left(m.lcUNC,Len(Alltrim(m.lcUNC))-1))
            Clear Dlls WNetGetConnection
      Endif
Endif
Return(m.lcFullPath)

What it will do is if you get a file that is stored on your local drive, then it will just show the normal fullpath(). If you get a file on a mapped drive, then it will replace the mapped drive with the actual UNC Path and combine that with the file to present you with a new fullpath using UNC path instead. The advantage of this is it won't be tied up to a mapped drive which may change from workstation to workstation.  Even if on one workstation, it is mapped to z:\ and on another to x:\, inside your app since it will be stored using the UNC path, it will always point to the proper location.

Cheers!