c#如何编写代码实现修改文件属性?

济南云服务器 2025年6月30日06:06:21C#教程c#如何编写代码实现修改文件属性?已关闭评论51阅读模式
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));
    }

济南云服务器
  • 本文由 发表于 2025年6月30日06:06:21
  • 转载请务必保留本文链接:http://news.hcsw666.com/2118