Search code examples
rubysketchup

Open a file from `My Documents` on Windows


I'm writing plugins for sketch up. I cannot find a simple way to append a text file from the My Documents directory on Windows. The problems I am having are:

  • opening with the current username
  • differences between Windows versions.

I need the code to open a file in append mode in My Documents on Windows 7 on a 32bit machine.


Solution

  • file = File.open(ENV['userprofile'] + "\\My Documents\\file.txt", "a")
    file.puts "text to append"
    file.close
    

    EDIT:
    Default location of user's documents is:

    On Windows 98 and Windows Me
    C:\My Documents
    On Windows 2000 and Windows XP
    %USERPROFILE%\My Documents
    On Windows Vista and later
    %USERPROFILE%\Documents

    Non-English versions of Windows XP or earlier will use directory names appropriate to that language.

    You can find the right path on Non-English systems in Windows Registry:

    require 'win32/registry'
    reg_path = 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
    reg = Win32::Registry::HKEY_CURRENT_USER.open( reg_path )
    right_path = reg['Personal']    # => C:\Documents and Settings\addo\Dokumenty