Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

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

How can I write to a hidden file?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...