【问题标题】:Open a file from `My Documents` on Windows在 Windows 上从“我的文档”打开文件
【发布时间】:2013-01-30 16:25:35
【问题描述】:

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

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

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

【问题讨论】:

  • 我的意思是在附加模式下打开一个文件 - 很抱歉造成混乱

标签: ruby sketchup


【解决方案1】:

您可以在 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。

【讨论】:

  • 谢谢,这真的很有帮助!
【解决方案2】:
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

【讨论】:

  • 虽然此方法确实有效,但它不会打开特定目录中的文件。在 Windows 上,这并不是特别有效。不过还是谢谢
  • 哦,完全忘了你问的是更具体的问题;)我会尝试更新。
  • 其实应该是ENV['userprofile'] + '/My Documents/file.txt'
  • Ruby 中的常量以大写字母开头。并且常量应该是常量:) 将Current_file 重命名为current_file
  • @CharlesCaldwell 你是对的,他想要“我的文件”,但我会避免这种情况,因为不是每个人都使用 EN Windows.. f.e.我有Dokumenty。检查stackoverflow.com/a/3492996/1136008
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多