1

I am trying to write to a file which has the following attributes - Hidden and ReadOnly. My process should be able to write to it but other processes have ReadOnly Access.

The procedure that I am following is:

  1. Check if file exists
  2. Remove the existing attributes on the file, i.e. hidden and readonly
  3. Finish writing to the file
  4. Apply the attributes (hidden and readonly) back to the file

I know that this is not the recommended way to use the File Attributes and write to a hidden file. Is there a nicer way to accomplish my task?

Thanks in advance.

user591410
  • 3,051
  • 5
  • 21
  • 30

3 Answers3

1

Yes, make your application impersonate a special account. Give file write permissions to that account on that file and read access to all other accounts.

The simplest way to run in the context of another user is to press shift and right click the exe-file, pick "Run as different user".

With a windows service you change the running account from the service properties. The same goes with Windows Scheduled tasks.

To change the running account "in the middle of the process" you need to do some more work, find a good article on the subject, like http://www.codeproject.com/Articles/4051/Windows-Impersonation-using-C .

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
  • Thanks for your suggestion. I am a novice here, could I get any references how to do that? And the app is currently a console app which should be converted into a windows service later on. Will the solution that you suggested have an impact on the app configuration later? Thanks. – user591410 Feb 17 '12 at 17:54
  • You can actually run the whole application in the context of that special user. With a Windows Service that is very easy, I updated my answer. – Albin Sunnanbo Feb 17 '12 at 19:51
0

As @Albin notes, the correct way to address the access issue is with file permissions, not attributes.

If the file is hidden because you don't want users to be able to view its contents, I'd suggest a simple (relatively lightweight) encryption mechanism would be a better solution than the hidden attribute.

Note, both the hidden and read-only attributes can be turned off by a user with sufficient privilege. And typically anyone can turn on the "show hidden files and folders" feature in Explorer.

David
  • 2,226
  • 32
  • 39
0

There's no need to remove the hidden attribute. I know of no other solution with the readonly one, though.

Loren Pechtel
  • 8,945
  • 3
  • 33
  • 45