Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a user from deleting, moving or renaming a file

What I am trying to do is while my program is using a file, I want to keep the user from renaming, deleting, or moving the file (well... a move is a delete and a create at a different location according to Windows FileSystemWatcher, but I digress).

It has been suggested that I use FileStream.Lock or use a Mutex. However, FileStream.Lock seems only to prevent the file from being modified which I am trying to allow. Also, I am very unsure as to if a mutex can lock a file, although I am still reading on it with in the .Net 4.0 library.

Does anyone have any advice on utilizing either one and if there is a code based solution to this problem?

like image 777
Blaze Phoenix Avatar asked Jul 03 '12 20:07

Blaze Phoenix


People also ask

How do I allow users to modify files but not delete them?

Open the Advanced Security Settings window, disable inheritance clearing all the entries, and add these: Allow Administrators "Full control" on "This folder, subfolders, and files" Allow SYSTEM "Full control" on "This folder, subfolders, and files"

How do I stop a file from being moved?

To actually prevent moving a folder, you need to prevent the deletion and the creation from occurring. So you need to deny the right to create folders. Users can still click and drag files to move them into other folders. Users can still delete and modify files.


1 Answers

When you are opening the file, you can specify the sharing mode.

Opening the file with FileAccess.Read gives you the ability to read the file, while FileShare.ReadWrite allows the file to continue to be edited, but not deleted or moved.

var fs = File.Open(@"C:\temp\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
MessageBox.Show("File Locked");  // While the messagebox is up, try to open or delete the file.
// Do your work here
fs.Close();
like image 145
John Koerner Avatar answered Sep 16 '22 16:09

John Koerner