在Ruby中将Windows路径转换为UNC

在Ruby中将Windows路径转换为UNC

问题描述:

我想将以下PATH转换为Ruby中的UNC路径.

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

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

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

A UNC路径要求您知道服务器和共享的名称,除非您正在寻找类似以下内容的路径,否则路径中都不存在这两个名称:
\\localhost\C$\Users\bla\bla2\asdf-ut-script.js

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

如果这是您想要的:

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