Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

You can use the backtick ` in Ruby to run a command line against the system. It will then return the result of the call.

Here's the official description at Ruby-Doc.org

Returns the standard output of running cmd in a subshell. The built-in syntax %x{...} uses this method. Sets $? to the process status.

`echo` #=> 'ECHO is on.' if ran on Windows

In Windows, there are special variables you can use to gather information such as a username:

echo %username%

Hence, you can use these two to gather the location of the user's My Documents folder (provided they are on Windows).

# Tested on Windows XP and 7
my_documents = File.join(`echo %userprofile%`.chomp, "My Documents")

Note: There is also a method in Ruby that makes system calls which is system. However, this returns a boolean which will not work in your case.

Also note that this solution will only work on Windows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top