如何使用c#创建、隐藏和取消隐藏文件夹

本文关键字:隐藏 取消 隐藏文件 文件夹 何使用 创建 | 更新日期: 2023-09-27 18:02:25

    private void button1_Click(object sender, EventArgs e)
    {
        if (!Directory.Exists("Test"))
        {
            DirectoryInfo dir = Directory.CreateDirectory("Test");
            dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
        }
        else
        {
            var dir = new DirectoryInfo("Test");
            dir.Attributes |= FileAttributes.Normal;
        }
        String password = "123";
        if ((textBox1.Text == password))
        {
            this.Hide();
            Form2 f2 = new Form2();
            f2.ShowDialog();
            var dir = new DirectoryInfo("Test");
            dir.Attributes |= FileAttributes.Normal;         
        }
        else
            MessageBox.Show("Incorrect Password or Username", "Problem");

所以,视觉方面看起来像这样:http://prntscr.com/7rj9hc所以你输入密码"123",然后点击解锁,理论上应该会使"测试"文件夹解除隐藏,你可以把东西放进去。然后第二种形式伴随着一个"锁定"按钮,它会使文件夹再次隐藏并关闭程序,这样你就可以打开和关闭文件夹来添加或删除一些东西。那么我该怎么做呢?任何解决方案,你会非常感激,请(如果你有时间)解释它是什么,每个部分都在做。请在您的解决方案中告诉我如何再次隐藏文件夹

如何使用c#创建、隐藏和取消隐藏文件夹

如果在按下解锁按钮时执行上述代码,则需要进行一些更改

private void button1_Click(object sender, EventArgs e)
{
    if (!Directory.Exists("Test"))
    {
        DirectoryInfo dir = Directory.CreateDirectory("Test");
        dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
    }
    // NO ELSE, the folder should remain hidden until you check the 
    // correctness of the password
    String password = "123";
    if ((textBox1.Text == password))
    {
        // This should be moved before opening the second form
        var dir = new DirectoryInfo("Test");
        // To remove the Hidden attribute Negate it and apply the bit AND 
        dir.Attributes = dir.Attributes & ~FileAttributes.Hidden;
        // A directory usually has the FileAttributes.Directory that has
        // a decimal value of 16 (10000 in binary). The Hidden attribute
        // has a decimal value of 2 (00010 in binary). So when your folder
        // is Hidden its decimal Attribute value is 18 (10010) 
        // Negating (~) the Hidden attribute you get the 11101 binary 
        // value that coupled to the current value of Attribute gives 
        // 10010 & 11101 = 10000 or just FileAttributes.Directory
        // Now you can hide the Unlock form, but please note
        // that a call to ShowDialog blocks the execution of
        // further code until you exit from the opened form
        this.Hide();
        Form2 f2 = new Form2();
        f2.ShowDialog();
        // No code will be executed here until you close the f2 instance
        .....
    }
    else
        MessageBox.Show("Incorrect Password or Username", "Problem");

要再次隐藏目录,您需要简单地将属性设置为隐藏标志,就像您创建目录

时所做的那样
   DirectoryInfo dir = new DirectoryInfo("Test");
   dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;

终于有一张纸条了。如果您的用户是其机器的管理员,并且可以使用操作系统

提供的标准接口更改隐藏文件和文件夹的属性,那么所有这些隐藏/取消隐藏工作都是完全无用的。