Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:*mediaPhotos2006-08.picasa.ini' is denied.

How can I write to a hidden file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...