BOSS
BOSS

Reputation: 1898

C# : edit file access control

hi i am working on c# project and i try to lock a file from being opened , copied or even deleted by using that code :

FileInfo fi = new FileInfo(textBox1.Text);
            FileSecurity ds = fi.GetAccessControl();
            ds.AddAccessRule(new FileSystemAccessRule("Authenticated Users",      FileSystemRights.FullControl, AccessControlType.Deny));
            fi.SetAccessControl(ds);

but when i open the file , it is opened and can be deleted , is there anything wrong on my code ?

by the way , that code works perfectly on anywhere but flash drive , i can block editing or copying files from computer , but on flash drive the application is useless .

Upvotes: 0

Views: 1606

Answers (1)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59151

What filesystem does your flash drive have? I'm guessing FAT32, rather than NTFS.

FAT32 has no concept of per-file ACLs (or as far as I know, no concept of ACLs whatsoever).

See this article:

http://technet.microsoft.com/en-us/library/cc783530(WS.10).aspx

On a FAT or FAT32 volume, you can set permissions for shared folders but not for files and folders within a shared folder. Moreover, share permissions on a FAT or FAT32 volume restrict network access only, not access by users working directly on the computer.

The only option will be to open the file in exclusive access mode to prevent others from changing it while you are reading it.

See this question (stolen from Vitaliy's comment):

How to lock file

The code from the accepted answer:

using (FileStream fs = 
       File.Open("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.None))
{
    // use fs
}

Upvotes: 2

Related Questions