Best way to make a file writeable in c#

送分小仙女□ 提交于 2019-12-09 07:30:29

问题


I'm trying to set flag that causes the Read Only check box to appear when you right click \ Properties on a file.

Thanks!


回答1:


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 IsReadOnly property on FileInfo essentially does the bit-flipping you would have to do manually in the second method.




回答2:


To set the read-only flag, in effect making the file non-writeable:

File.SetAttributes(filePath,
    File.GetAttributes(filePath) | FileAttributes.ReadOnly);

To remove the read-only flag, in effect making the file writeable:

File.SetAttributes(filePath,
    File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);

To toggle the 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 .Normal or .ReadOnly you might end up losing other flags in the process.




回答3:


c# :

File.SetAttributes(filePath, FileAttributes.Normal);

File.SetAttributes(filePath, FileAttributes.ReadOnly);



来源:https://stackoverflow.com/questions/1202022/best-way-to-make-a-file-writeable-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!