在Ruby中将Windows路径转换为UNC [英] Convert windows path to UNC in Ruby

查看:93
本文介绍了在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

这篇关于在Ruby中将Windows路径转换为UNC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆