使文件在c#中可写的最佳方法

wil*_*ill 35 .net c# file file-attributes

我正在尝试设置标志,导致Read Only当您right click \ Properties在文件上时出现复选框.

谢谢!

Rex*_*x M 64

两种方式:

System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
fileInfo.IsReadOnly = true/false;
Run Code Online (Sandbox Code Playgroud)

要么

// Careful! This will clear other file flags e.g. FileAttributes.Hidden
File.SetAttributes(filePath, FileAttributes.ReadOnly/FileAttributes.Normal);
Run Code Online (Sandbox Code Playgroud)

FileInfo上的IsReadOnly属性实际上是在第二种方法中手动完成的位翻转.

  • 请注意,这将有效地同时清除同一文件上的其他标志.隐藏文件将变为可见,系统文件将变为非系统文件等. (7认同)
  • 第一种方法缩短为`new FileInfo(filePath){IsReadOnly = false};`,这很整洁! (2认同)

ang*_*son 37

设置只读标志,实际上使文件不可写:

File.SetAttributes(filePath,
    File.GetAttributes(filePath) | FileAttributes.ReadOnly);
Run Code Online (Sandbox Code Playgroud)

删除只读标志,实际上使文件可写:

File.SetAttributes(filePath,
    File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
Run Code Online (Sandbox Code Playgroud)

切换只读标志,使其与现在的任何标志相反:

File.SetAttributes(filePath,
    File.GetAttributes(filePath) ^ FileAttributes.ReadOnly);
Run Code Online (Sandbox Code Playgroud)

这基本上是位掩码.您设置一个特定位来设置只读标志,清除它以删除该标志.

请注意,上述代码不会更改文件的任何其他属性.换句话说,如果在执行上面的代码之前隐藏了文件,那么它也会在之后保持隐藏状态.如果只是将文件属性设置为,.Normal或者.ReadOnly最终可能会丢失其他标志.