esac esac - 1 year ago 111
C# Question

How do I write to a hidden file?

I am using the TextWriter to try to write to a hidden file, and it is throwing an exception. I can't seem to figure out how to write to a hidden file.

using (TextWriter tw = new StreamWriter(filename))


Unhandled Exception: System.UnauthorizedAccessException:
Access to the path 'E:\*\media\Photos\2006-08\.picasa.ini' is denied.

How can I write to a hidden file?

Answer Source

EDIT 2: This answer solve the problem, but is not the correct way to deal with the problem. You should look for Lucero's answer.

Took this answer from:

1- Set File as Visible so it can be overwritten

// Get file info
FileInfo myFile= new FileInfo(Environment.CurrentDirectory + @"\hiddenFile.txt");

// Remove the hidden attribute of the file
myFile.Attributes &= ~FileAttributes.Hidden;

2- Make changes to the file

// Do foo...

3- Set back file as hidden

// Put it back as hidden
myFile.Attributes |= FileAttributes.Hidden;

EDIT: I fixed some problem on my answer as mentionned by briler

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download