【问题标题】:Check if file is open in any application检查文件是否在任何应用程序中打开
【发布时间】:2011-11-04 14:25:00
【问题描述】:

是否可以检查文件或捆绑包是否被任何应用程序打开?例如,假设我知道/Users/Foo/AwesomeDocument.txt 存在并且它在TextEdit 中打开,我可以从我的应用程序中可靠地检查文档是否打开? 我可以接受仅适用于通过 NSDocumentController 打开的文档的解决方案。

【问题讨论】:

  • 哦,拜托,我不想为我创建的每个问题开始赏金......
  • 您是否考虑过您可能提出了一个难题?
  • @RobKeniger 是的,这就是我在这里问的原因。

标签: macos cocoa nsdocument


【解决方案1】:

您可以使用 NSTask 运行 shell 命令 lsof | grep "Document.txt" 然后解析结果,尽管这种方法有点慢。我不知道实现这一点的原生 Cocoa 方式。

【讨论】:

  • 遗憾的是,这不适用于通过NSDocumentController 打开的文件,因为它没有始终打开文件句柄。
【解决方案2】:

你的意思是这样吗?

例如,在 Applescript 中:

tell application "TextEdit"
    set theDocument to document of window 1
    return theDocument
end tell

【讨论】:

  • 不完全是,我想检查一个已知文件是否打开,而不是当前在 TextEdit 中打开的文件(所以这个的反向版本会很棒)。它也应该跨空间工作=/
【解决方案3】:
tell application "TextEdit"
    set theDocuments to every document
    repeat with aDocument in theDocuments
        if (path of aDocument) as string is equal to "/test.txt" then
            display dialog "found"
        end if
    end repeat
end tell

【讨论】:

  • 对不起,我仍然需要它。询问每个应用程序是否打开了文档是我并不真正想要的一些开销,我宁愿只使用路径并知道文件是否在某处打开。
【解决方案4】:

从 10.7 开始,您可能想尝试使用 NSFileCoordinator。请记住,并非每个应用程序都必须实现NSFilePresenter 并使用NSDocument

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多