How do I write to a hidden file?

后端 未结 6 1304
情话喂你
情话喂你 2020-12-09 09:08

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         


        
6条回答
  •  无人及你
    2020-12-09 09:40

    Once you've opened a file, you can change its attributes (including to readonly) and continue writing to it. This is one way to prevent a file from being overwritten by other processes.

    So it would seem to be possible to unhide the file, open it, then reset it to hidden, even while you've got it open.

    For example, the following code works:

    public void WriteToHiddenFile(string fname)
    {
        TextWriter    outf;
        FileInfo      info;  
    
        info = new FileInfo(fname);
        info.Attributes = FileAttributes.Normal;    // Set file to unhidden
        outf = new StreamWriter(fname);             // Open file for writing
        info.Attributes = FileAttributes.Hidden;    // Set back to hidden
        outf.WriteLine("test output.");             // Write to file
        outf.Close();                               // Close file
    }
    

    Note that the file remains hidden while the process writes to it.

提交回复
热议问题