简体   繁体   English

将长文件名转换为短文件名(8.3)

[英]Convert long filename to short filename (8.3)

I want to convert long filenames/path to short filenames (8.3). 我想将长文件名/路径转换为短文件名(8.3)。 I'm developing a script that calls a command line tool that only accepts short filenames. 我正在开发一个调用命令行工具的脚本,该工具只接受短文件名。

So i need to convert 所以我需要转换

C:\\Ruby193\\bin\\test\\New Text Document.txt

to

C:\\Ruby193\\bin\\test\\NEWTEX~1.TXT

So far i found How to get long filename from ARGV which uses WIN32API to convert short to long filenames (the opposite of what I want to achieve). 到目前为止,我发现如何从ARGV获取长文件名,它使用WIN32API将短文件名转换为长文件名(与我想要实现的相反)。

Is there any way to get the short filename in Ruby? 有没有办法在Ruby中获取短文件名?

You can do this using FFI ; 你可以用FFI做到这一点; there's actually an example that covers your exact scenario in their wiki under the heading "Convert a path to 8.3 style pathname": 实际上有一个例子涵盖了他们的wiki中标题为“将路径转换为8.3样式路径名”的确切场景:

require 'ffi'

module Win
  extend FFI::Library
  ffi_lib 'kernel32'
  ffi_convention :stdcall

  attach_function :path_to_8_3, :GetShortPathNameA, [:pointer, :pointer, :uint], :uint
end
out = FFI::MemoryPointer.new 256 # bytes
Win.path_to_8_3("c:\\program files", out, out.length)
p out.get_string # be careful, the path/file you convert to 8.3 must exist or this will be empty

This ruby code uses getShortPathName and don't need additional modules to be installed. 此ruby代码使用getShortPathName ,不需要安装其他模块。

def get_short_win32_filename(long_name)
    require 'win32api'
    win_func = Win32API.new("kernel32","GetShortPathName","PPL"," L")
    buf = 0.chr * 256
    buf[0..long_name.length-1] = long_name
    win_func.call(long_name, buf, buf.length)
    return buf.split(0.chr).first
end

The windows function you require is GetShortPathName . 您需要的Windows功能是GetShortPathName You could use that in the same manner as described in your linked post. 您可以按照链接帖子中描述的相同方式使用它。

EDIT: sample usage of GetShortPathName (just as a quick example) - shortname will contain "C:\\LONGFO~1\\LONGFI~1.TXT" and returned value is 24. 编辑:GetShortPathName的示例用法(仅作为简单示例) - 短名称将包含“C:\\ LONGFO~1 \\ LONGFI~1.TXT”,返回值为24。

TCHAR* longname = "C:\\long folder name\\long file name.txt";
TCHAR* shortname = new TCHAR[256];
GetShortPathName(longname,shortname,256);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM