Question

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.

Was it helpful?

Solution

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 .

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top