Windows操作系统中,每一个文件都有一个系统定义的属性,比如,只读、隐藏等,在系统中,用户可以根据自己的实际需求更改这些属性,但是,我们如何通过c#编程语言编写代码解决这个问题呢?下面,济南网站建设小编就来为大家演示,通过c#编程语言编写源代码实现随意更改文件属性的小方法,有需要的朋友可以过来参考一下。
关键代码:
static void Main() { string filePath = @"C:\temp\test.txt"; // 获取当前文件属性 FileAttributes attributes = File.GetAttributes(filePath); Console.WriteLine("原始属性:" + attributes); // 设置文件为只读并隐藏 File.SetAttributes(filePath, FileAttributes.ReadOnly | FileAttributes.Hidden); Console.WriteLine("新属性(只读+隐藏):" + File.GetAttributes(filePath)); // 取消只读和隐藏属性 attributes = File.GetAttributes(filePath); attributes &= ~FileAttributes.ReadOnly; // 移除只读 attributes &= ~FileAttributes.Hidden; // 移除隐藏 File.SetAttributes(filePath, attributes); Console.WriteLine("恢复后的属性:" + File.GetAttributes(filePath)); }
评论