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?
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 aFileMode.Createon a file which already exists).Therefore, use
FileMode.OpenOrCreateto make sure that the file is opened or created even if it is hidden, or justFileMode.Openif you do not want to create it if it doesn’t exist.When
FileMode.OpenOrCreateis 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.If you use .NET 4.5 or later, there is a new overload which prevents the disposal of the
StreamWriterto also dispose the underlying stream. The code could then be written slighly more intuitively like this: