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?
Using the command line command dir /ah displays the files with the Hidden attribute.
A hidden file is a file which has the hidden attribute turned on so that it is not visible to users when exploring or listing files. Hidden files are used for storage of user preferences or for preservation of the state of utilities. They are created frequently by various system or application utilities.
Select the Start button, then select Control Panel > Appearance and Personalization. Select Folder Options, then select the View tab. Under Advanced settings, select Show hidden files, folders, and drives, and then select OK.
A hidden file is any file with the hidden attribute turned on. Just as you'd expect, a file or folder with this attribute toggled on is invisible while browsing through folders—you can't see any of them without explicitly allowing all of them to be seen.
It seems that the problem is that kind of a File.Exists()
check is done internally, which fails if the file is hidden (e.g. tries to do a FileMode.Create
on a file which already exists).
Therefore, use FileMode.OpenOrCreate
to make sure that the file is opened or created even if it is hidden, or just FileMode.Open
if you do not want to create it if it doesn't exist.
When FileMode.OpenOrCreate
is used though, the file will not be truncated, so you should set its length at the end to make sure that there is no leftover after the end of the text.
using (FileStream fs = new FileStream(filename, FileMode.Open)) { using (TextWriter tw = new StreamWriter(fs)) { // Write your data here... tw.WriteLine("foo"); // Flush the writer in order to get a correct stream position for truncating tw.Flush(); // Set the stream length to the current position in order to truncate leftover text fs.SetLength(fs.Position); } }
If you use .NET 4.5 or later, there is a new overload which prevents the disposal of the StreamWriter
to also dispose the underlying stream. The code could then be written slighly more intuitively like this:
using (FileStream fs = new FileStream(filename, FileMode.Open)) { using (TextWriter tw = new StreamWriter(fs, Encoding.UTF8, 1024, true)) { // Write your data here... tw.WriteLine("foo"); } // Set the stream length to the current position in order to truncate leftover text fs.SetLength(fs.Position); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With