在 C# 中使文件可写的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1202022/
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
Best way to make a file writeable in c#
提问by will
I'm trying to set flag that causes the Read Onlycheck box to appear when you right click \ Propertieson a file.
我正在尝试设置标志,使Read Only您right click \ Properties在文件上时出现复选框。
Thanks!
谢谢!
采纳答案by Rex M
Two ways:
两种方式:
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
fileInfo.IsReadOnly = true/false;
or
或者
// Careful! This will clear other file flags e.g. `FileAttributes.Hidden`
File.SetAttributes(filePath, FileAttributes.ReadOnly/FileAttributes.Normal);
The IsReadOnlyproperty on FileInfoessentially does the bit-flipping you would have to do manually in the second method.
该IsReadOnly物业FileInfo本质上是做位翻转你就必须在第二个方法做手工。
回答by will
C# :
C# :
File.SetAttributes(filePath, FileAttributes.Normal);
File.SetAttributes(filePath, FileAttributes.ReadOnly);
回答by Lasse V. Karlsen
To setthe read-only flag, in effect making the file non-writeable:
要设置只读标志,实际上使文件不可写:
File.SetAttributes(filePath,
File.GetAttributes(filePath) | FileAttributes.ReadOnly);
To removethe read-only flag, in effect making the file writeable:
要删除只读标志,实际上使文件可写:
File.SetAttributes(filePath,
File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
To togglethe read-only flag, making it the opposite of whatever it is right now:
要切换只读标志,使其与现在相反:
File.SetAttributes(filePath,
File.GetAttributes(filePath) ^ FileAttributes.ReadOnly);
This is basically bitmasks in effect. You set a specific bit to set the read-only flag, you clear it to remove the flag.
这基本上是有效的位掩码。您设置一个特定位来设置只读标志,清除它以删除该标志。
Note that the above code will not change any other properties of the file. In other words, if the file was hidden before you executed the above code, it will stay hidden afterwards as well. If you simply set the file attributes to .Normalor .ReadOnlyyou might end up losing other flags in the process.
请注意,上述代码不会更改文件的任何其他属性。换句话说,如果文件在您执行上述代码之前被隐藏,它也会在之后保持隐藏状态。如果您只是将文件属性设置为.Normal或者.ReadOnly您可能最终会在此过程中丢失其他标志。

