Search code examples
c#windows-10uwpstoragefilewindows-10-desktop

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


I have a basic UWP app running on Windows 10 on the desktop. The app defines a custom file format and lets the user open and edit documents.

I use a FileOpenPicker to let the user pick the file.

My question is: how can I prevent that the user renames/moves/deletes the document outside of my app (for example in the Windows explorer) while it is open in my app?

Word Mobile locks open documents. If I try to rename an open document in the Windows explorer I get an error:

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

I want to achieve the same. I suspect that the Word Mobile app is opening the file in a special mode or locking it somehow. I tried the various Storagefile.OpenXXX() methods, but no luck:

// 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();

Solution

  • There is a ShareMode that you can set on files, if you set this to "None" then nobody else can open or modify this file as long as you're holding it open:

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

    This uses System.IO which should be available to you. Full documentation here: https://msdn.microsoft.com/en-us/library/system.io.fileshare(v=vs.110).aspx

    Would that help you?