0

I'm working on a program that acts much like dropbox but locally for my business. I have it setup where some users can't write to some files/directories but they can still write locally. It's not a huge problem, I can just redownload the file/directory but it would be nice if I could just lock it. (they would still need read though)

David
  • 388
  • 1
  • 5
  • 23

2 Answers2

2

I can think of couple of solutions:

  • Have your application keep the file opened as read only. This may cause some issues if the number of files grows large, is you will likely hit some ceilings, either in memory, or handle limits.

    See this excellent technet blog for some information on handle limits http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx

  • Use NTFS permissions. If you run your application as another user, take ownership of the file and allow other users read only access, it should help. Since you are in a business environment you may have that level of control of running applications as services or on startup.

    A nice SO post on NTFS permissions Setting NTFS permissions in C#.NET

Community
  • 1
  • 1
Phil Martin
  • 456
  • 4
  • 4
  • Some issues I have: I don't think I would like to use the first for the reasons you mentioned, the second would require it run as admin or service which isn't optimal, and it wouldn't only be on company computers so AD solutions are off the table. On second thought I could run it as a service, but mocking with NTFS permissions is something I would like to avoid. – David Nov 16 '12 at 01:29
  • I'm afraid I don't think you have a lot of options. You want to lock a file, that sounds like something a file system is ideally used to solve. Avoiding NTFS permissions may be something you might want to consider. Also, it would need to run as an Admin user, just a user with sufficient permssions to work with that particular folder. – Phil Martin Nov 16 '12 at 02:23
  • I meant "reconsider". Sorry if there was confusion. I sure hope you find a solution that works for you, it sound like quite the fun application to write. – Phil Martin Nov 16 '12 at 03:13
  • I really like your answer but It's probably not the best way for me to go this time, I did up vote though. – David Nov 16 '12 at 13:27
1

I suggest you set the Read Only Attribute using the File.SetAttributes method.

To Set the file as Read Only:

File.SetAttributes(@"C:\Users\Owner\Desktop\file.txt", FileAttributes.ReadOnly);

To Set the file back to normal:

File.SetAttributes(@"C:\Users\Owner\Desktop\file.txt", FileAttributes.Normal);

You can check to see if the file is read only, and then throw an error :

System.IO.FileInfo fileInfo = new System.IO.FileInfo(@"C:\Users\Owner\Desktop\file.txt");
if (fileInfo.IsReadOnly)
{
    //...Alert user that this file cannot be deleted
}
else
{
    //... Delete the file here
}
Dave Lucre
  • 1,045
  • 1
  • 14
  • 15