首页 文章

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

提问于
浏览
1

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

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

我的问题是:在我的应用程序中打开文档时,如何防止用户在我的应用程序之外重命名/移动/删除文档(例如在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();

1 回答

  • 1

    您可以在文件上设置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

    这对你有帮助吗?

相关问题