在Windows上打开“我的文档”中的文件

时间:2013-01-30 16:25:35

标签: ruby sketchup

我正在为草图编写插件。我找不到一种简单的方法来附加Windows上My Documents目录中的文本文件。我遇到的问题是:

  • 以当前用户名打开
  • Windows版本之间的差异。

我需要代码在32位计算机上的Windows 7上的My Documents中以附加模式打开文件。

2 个答案:

答案 0 :(得分:2)

您可以使用Ruby中的反引号来对系统运行命令行。然后它将返回调用的结果。

以下是Ruby-Doc.org

的官方说明
  

返回子shell中运行cmd的标准输出。内置   语法%x {...}使用此方法。设置$?进程状态。

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

在Windows中,您可以使用special variables来收集用户名等信息:

echo %username%

因此,您可以使用这两个来收集用户的“我的文档”文件夹的位置(前提是它们在Windows上)。

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

注意: Ruby中还有一个方法可以进行system的系统调用。但是,这会返回一个布尔值,在您的情况下不起作用。

另请注意,此解决方案可在Windows上运行。

答案 1 :(得分:1)

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

修改
Default location of user's documents 是:

在Windows 98和Windows Me上
C:\My Documents
在Windows 2000和Windows XP上
%USERPROFILE%\My Documents
在Windows Vista及更高版本中
%USERPROFILE%\Documents

  非英语版本 Windows XP 早期将使用目录名称   适合那种语言。

You can find the right path在Windows注册表中的非英语系统上:

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