C# 如何写入隐藏文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2246990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:45:10  来源:igfitidea点击:

How do I write to a hidden file?

c#filehidden

提问by esac

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.

我正在使用 TextWriter 尝试写入隐藏文件,但它引发了异常。我似乎无法弄清楚如何写入隐藏文件。

using (TextWriter tw = new StreamWriter(filename))
{
    tw.WriteLine("foo");
    tw.Close();
}

Exception:

例外:

Unhandled Exception: System.UnauthorizedAccessException: 
Access to the path 'E:\*\media\Photos06-08\.picasa.ini' is denied.

How can I write to a hidden file?

如何写入隐藏文件?

采纳答案by Pierre-Luc Champigny

EDIT 2: This answer solve the problem, but is not the correct way to deal with the problem. You should look for Lucero's answer.

编辑 2:此答案解决了问题,但不是处理问题的正确方法。您应该寻找 Lucero 的答案。



Took this answer from: http://www.dotnetspark.com/Forum/314-accessing-hidden-files-and-write-it.aspx

这个答案来自:http: //www.dotnetspark.com/Forum/314-accessing-hidden-files-and-write-it.aspx

1- Set File as Visible so it can be overwritten

1-将文件设置为可见,以便可以覆盖

// Get file info
FileInfo myFile= new FileInfo(Environment.CurrentDirectory + @"\hiddenFile.txt");

// Remove the hidden attribute of the file
myFile.Attributes &= ~FileAttributes.Hidden;

2- Make changes to the file

2- 更改文件

// Do foo...

3- Set back file as hidden

3-将文件设置为隐藏

// Put it back as hidden
myFile.Attributes |= FileAttributes.Hidden;

EDIT: I fixed some problem on my answer as mentionned by briler

编辑:我解决了 briler 提到的一些问题

回答by Tomas Vana

If that's an option for you you could try to use File.SetAttributesto remove the hidden attribute temporarily, do your work and then set it back to the previous state.

如果这是您的一个选项,您可以尝试使用File.SetAttributes暂时删除隐藏属性,完成您的工作,然后将其设置回以前的状态。

回答by viky

You can unhide the file before writing into it and after complete writing hide it again.

您可以在写入文件之前取消隐藏文件,并在完成写入后再次隐藏它。

回答by David R Tribble

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.

请注意,该文件在进程写入时保持隐藏状态。

回答by Lucero

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.Createon a file which already exists).

似乎问题在于这种File.Exists()检查是在内部完成的,如果文件被隐藏(例如尝试对FileMode.Create已经存在的文件执行),则该检查会失败。

Therefore, use FileMode.OpenOrCreateto make sure that the file is opened or created even if it is hidden, or just FileMode.Openif you do not want to create it if it doesn't exist.

因此,用于FileMode.OpenOrCreate确保文件被打开或创建,即使它是隐藏的,或者FileMode.Open如果它不存在,你不想创建它。

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.

FileMode.OpenOrCreate但是,当使用时,文件不会被截断,因此您应该在末尾设置其长度以确保文本结束后没有剩余。

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 StreamWriterto also dispose the underlying stream. The code could then be written slighly more intuitively like this:

如果您使用 .NET 4.5 或更高版本,则有一个新的重载会阻止处置StreamWriter以同时处置基础流。然后可以像这样更直观地编写代码:

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

回答by briler

Edit : Pierre-Luc Champigny answer wasinccorect, but now fixed according to mine, I'm Leaving it behind as reference

编辑:Pierre-Luc Champigny 的回答正确,但现在根据我的进行修正,我把它留在后面作为参考

myFile.Attributes |= FileAttributes.Normal;

doesn't remove the Hidden attribute from the file. in order to remove unhidden attribute use :

不会从文件中删除 Hidden 属性。为了删除未隐藏的属性,请使用:

FileInfo .Attributes &= ~FileAttributes.Hidden; 

This code checks if the file exists it make it unhidden. before writing once finish it set it as hidden again. I also set the normal attribute in case the didn't exist - you do not have to use it

此代码检查文件是否存在以使其不隐藏。在写入完成之前,将其再次设置为隐藏。如果不存在,我还设置了 normal 属性 - 您不必使用它

// if do not exists it creates it.
FileInfo FileInfo = new FileInfo(FileName);
if (true == FileInfo .Exists)
{
   // remove the hidden attribute from the file
   FileInfo .Attributes &= ~FileAttributes.Hidden; 
} //if it doesn't exist StreamWriter will create it
using (StreamWriter fileWriter = new StreamWriter(FileName))
{
   fileWriter.WriteLine("Write something");
}
 // set the file as hidden
FileInfo.Attributes |= FileAttributes.Hidden;