如何锁定打开的 StorageFile 以防止用户在我的应用程序之外重命名它?

How to lock open StorageFile to prevent user from renaming it outside of my app?

我在桌面 Windows 10 上有一个基本的 UWP 应用 运行。该应用程序定义了自定义文件格式并允许用户打开和编辑文档。

我使用 FileOpenPicker 让用户选择文件。

我的问题是:当文档在我的应用程序中打开时,如何防止用户 renames/moves/deletes 我的应用程序之外的文档(例如在 Windows 资源管理器中)?

Word Mobile 锁定打开的文档。如果我尝试在 Windows 资源管理器中重命名打开的文档,我会收到错误消息:

"The action can't be completed because the file is open in Runtime Broker. Close the file and try again."

我也想达到同样的效果。我怀疑 Word Mobile 应用程序以特殊模式打开文件或以某种方式锁定文件。我尝试了各种 Storagefile.OpenXXX() 方法,但没有成功:

// None of these seem to exclusively lock the file:
stream = await file.OpenStreamForWriteAsync();
stream = await file.OpenTransactedWriteAsync();
stream = await file.OpenAsync(FileAccessMode.ReadWrite);
stream = await file.OpenReadAsync();

您可以在文件上设置一个 ShareMode,如果您将其设置为 "None" 那么只要您保持打开状态,其他人就无法打开或修改该文件:

new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read);

这使用了 System.IO,您应该可以使用。完整文档在这里: https://msdn.microsoft.com/en-us/library/system.io.fileshare(v=vs.110).aspx

对你有帮助吗?

我相信这应该是您正在寻找的电话:

file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowOnlyReaders);

来自: https://docs.microsoft.com/en-us/uwp/api/windows.storage.storageopenoptions?view=winrt-19041