wmitchell
wmitchell

Reputation: 5725

Convert windows path to UNC in Ruby

I'd like to convert the following PATH into a UNC path in Ruby.

C:/Users/bla/bla2/asdf-ut-script.js

Upvotes: 1

Views: 1633

Answers (1)

Phrogz
Phrogz

Reputation: 303206

A UNC path requires that you know the name of the server and share, neither of which are present in your path, unless you're looking for something like:
\\localhost\C$\Users\bla\bla2\asdf-ut-script.js

If this is what you want:

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

puts File.to_unc( "C:/Users/bla/bla2/asdf-ut-script.js" )
#=> \\localhost\C$\Users\bla\bla2\asdf-ut-script.js

puts File.to_unc( "C:/Users/bla/bla2/asdf-ut-script.js", 'filepile' )
#=> \\filepile\C$\Users\bla\bla2\asdf-ut-script.js

puts File.to_unc( "/bla/bla2/asdf-ut-script.js", 'filepile', 'HOME' )
#=> \\filepile\HOME\bla\bla2\asdf-ut-script.js

Upvotes: 1

Related Questions