esac esac - 1 month ago 7
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))
{
tw.WriteLine("foo");
tw.Close();
}


Exception:

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

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: http://www.dotnetspark.com/Forum/314-accessing-hidden-files-and-write-it.aspx

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

Comments