Search code examples
c#recommendation-enginefile-writinghidden-files

Recommended way of writing to a Hidden/ReadOnly File C#


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.


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 .