Convert long file name to short file name (8.3)

I want to convert long file names / path to short file names (8.3). I am developing a script that invokes a command line tool that accepts only short file names.

So I need to convert

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

to

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

So far I have found How to get a long file name from ARGV , which uses WIN32API to convert short and long file names (contrary to what I want to achieve).

Is there a way to get the short file name in Ruby?

+3
source share
3 answers

This ruby ​​code uses getShortPathName and does not need additional modules for installation.

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
+3
source

, FFI; , " 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
+3

windows - GetShortPathName. , .

EDIT: GetShortPathName ( ) - shortname "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);
+1

All Articles