0

Is it possible in Ruby running on Windows to resolve a local file to its UNC path.

For example: D:\hello.jpg should resolve to \\server01\DShare\hello.jpg

Drive letter D is shared as DShare on server01. I also want this to work for any given drive letter that is shared.

Similar question was asked in Python: Python 2: Get network share path from drive letter

If possible, I'd prefer for it to be achieved without installing additional Gems.

This code almost does it, but I want to use the Share name rather than the admin share $

def File.to_unc( path, server="localhost", share=nil )
  parts = path.split(File::SEPARATOR)
  parts.shift while parts.first.empty?
  if share
    parts.unshift share
  else
    # Assumes the drive will always be a single letter up front
    parts[0] = "#{parts[0][0,1]}$" 
  end
  parts.unshift server
  "\\\\#{parts.join('\\')}"
end
Sam
  • 602
  • 9
  • 21
  • The easiest way is probally just to shell out and [use a powershell script](https://stackoverflow.com/questions/21482825/find-unc-path-of-a-network-drive). – max Oct 12 '20 at 15:19
  • Thanks, this will be run as part of some automation across potentially millions of files, so not sure PowerShell, in my case, will be the most efficient way to tackle this problem. – Sam Oct 12 '20 at 15:21

0 Answers0