当前位置: 首页 > news >正文

10.2 目录(文件夹)操作

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。

10.2.1 DirectoryInfo类

DirectoryInfo类可以获得目录信息。

DirectoryInfo常用属性:

  1. Name:获取DirectoryInfo实例的名称,例如:c:\windows\system32将返回system32。
  2. FullName:获取目录或文件的完整目录。例如:c:\windows\system32将返回c:\windows\system32。
  3. Attributes:目录的属性。
  4. Exists:目录是否存在。
  5. CreationTime:目录的创建时间。
  6. LastWriteTime:目录的最后修改时间。
  7. Parent:目录的父目录。

DirectoryInfo常用方法:

  1. Create:创建目录。
  2. Delete:删除目录,使用此方法带参数的重载可以实现删除目录下的子目录和文件,否则只能删除空目录。
  3. MoveTo:移动目录。注意:此方法只能在同一个磁盘分区下移动。
  4. GetDirectories:返回当前目录的子目录列表,这是一个DirectoryInfo数组。
  1. GetFiles:返回当前目录的文件列表,这是一个FileInfo数组。关于FileInfo类,请参看第10.3.1节。
10.2.1.1 获取目录信息

【例 10.2【项目:code10-002】获得计算机上某个目录的信息。

当选择某个文件夹后,立即在文本框中显示该文件夹的相关信息:

     private void button1_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.ShowNewFolderButton = false;

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            string folderpath = fbd.SelectedPath;

            DirectoryInfo di = new DirectoryInfo(folderpath);

            textBox1.Text = "文件夹:" + di.Name + "\r\n";

            textBox1.Text += "路径:" + di.FullName + "\r\n";

            textBox1.Text += "创建日期:" + di.CreationTime.ToString("yyyy-MM-dd") + "\r\n";

            textBox1.Text += "最后修改日期:" + di.LastWriteTime.ToString("yyyy-MM-dd") + "\r\n";

            textBox1.Text += "属性:" + getFolderAttr(di.Attributes) + "\r\n";

        }

        //获得文件夹属性

        private string getFolderAttr(FileAttributes attr)

        {

            string strAttr = "";

            if((attr & FileAttributes.Archive)==FileAttributes.Archive)

                strAttr += " 备份";

            if ((attr & FileAttributes.Hidden) == FileAttributes.Hidden)

                strAttr += " 隐藏";

            if ((attr & FileAttributes.Compressed) == FileAttributes.Compressed)

                strAttr += " 压缩";

            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)

                strAttr += " 目录";

            if ((attr & FileAttributes.Encrypted) == FileAttributes.Encrypted)

                strAttr += " 加密";

            if ((attr & FileAttributes.Offline) == FileAttributes.Offline)

                strAttr += " 脱机";

            if ((attr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)

                strAttr += " 只读";

            if ((attr & FileAttributes.System) == FileAttributes.System)

                strAttr += " 系统";

            if ((attr & FileAttributes.Temporary) == FileAttributes.Temporary)

                strAttr += " 临时";

            return strAttr;

        }

运行结果如下图所示:

图10-2 获取目录信息

10.2.1.2 获取子目录和文件

获取当前目录的子目录和所有文件主要是使用GetDirectories和GetFiles方法,这两个方法返回包含的子目录(DirectoryInfo数组)和文件(FileInfo数组),只需要分别遍历这两个数组即可获得相关信息。

【例 10.3【项目:code10-003】获得子目录和文件。

        private void button1_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            label1.Text = fbd.SelectedPath;

            DirectoryInfo di = new DirectoryInfo(label1.Text);

            listBox1.Items.Clear();

            //遍历当前目录下的子目录

            foreach (DirectoryInfo subdi in di.GetDirectories())

            {

                listBox1.Items.Add("目录:" + subdi.Name);

            }

            //遍历当前目录下的文件

            foreach (FileInfo fi in di.GetFiles())

            {

                listBox1.Items.Add("文件:" + fi.Name);

            }

        }

运行结果如下图所示:

图10-3 获得选定目录的子目录和文件

10.2.1.3 设置目录属性

通过DirectoryInfo类的Attributes属性可以获得和设置目录属性。Attributes的值是一个FileAttributes枚举,它提供了文件和目录的属性。

表10-1 FileAttributes枚举常用成员及对应属性说明

成员名称

对应属性说明

成员名称

对应属性说明

Archive

备份

Normal

正常

Compressed

压缩

Offline

脱机

Directory

指示这是目录

ReadOnly

只读

Encrypted

加密

System

系统

Hidden

隐藏

Temporary

临时

判断现有属性是否包括某个属性,请使用:现有属性 And 某个属性:

表10-2 判断是否包含只读属性

属性

十进制值

操作

二进制值

十六进制值

N+R

129

&

(And)

1

0

0

0

0

0

0

1

81

ReadOnly

1

0

0

0

0

0

0

0

1

1

ReadOnly

1

0

0

0

0

0

0

0

1

1

现有属性基础上增加某个属性,请使用:现有属性 Or 某个属性:

表10-3 增加隐藏属性

属性

十进制值

操作

二进制值

十六进制值

Normal

128

|

(Or)

1

0

0

0

0

0

0

0

80

Hidden

2

0

0

0

0

0

0

1

0

2

N+H

130

1

0

0

0

0

0

1

0

82

从现有属性中排除某个属性,请使用:现有属性 Xor 某个属性:

表10-4 排除只读属性

属性

十进制值

操作

二进制值

十六进制值

N+R

129

^

(Xor)

1

0

0

0

0

0

0

1

81

ReadOnly

1

0

0

0

0

0

0

0

1

1

Normal

128

1

0

0

0

0

0

0

0

80

注意:微软提供的很多Api常量和.Net常量都类似于FileAttributes常量枚举,即按照 0、1、2、4、8……这样定义的,很方便使用&、|、^等位运算符。

【例 10.4【项目:code10-004】设置目录属性。

        //选择目录,并获得其属性

        private void button1_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            label1.Text = fbd.SelectedPath;

            DirectoryInfo di = new DirectoryInfo(label1.Text);

            //目录有只读属性,那么勾选CheckBox1

            if ((di.Attributes & FileAttributes.ReadOnly) ==FileAttributes.ReadOnly )

                checkBox1.Checked = true;

            //目录有隐藏属性,那么勾选CheckBox2

            if ((di.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)

                checkBox2.Checked = true;

            //目录有系统属性,那么勾选CheckBox3

            if ((di.Attributes & FileAttributes.System) == FileAttributes.System)

                checkBox3.Checked = true;

        }

        //设置指定目录的属性

        private void button2_Click(object sender, EventArgs e)

        {

            DirectoryInfo di = new DirectoryInfo(label1.Text);

            if (di.Exists == false)

                return;

            FileAttributes fa = di.Attributes;

            if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)

            {

                //如果有只读属性,而设置取消只读,那么使用异或方式

                if (checkBox1.Checked == false)

                    fa = fa ^ FileAttributes.ReadOnly;

            }

           else

            {

                //如果没有只读属性,而设置只读,那么使用或方式

                if (checkBox1.Checked == true)

                    fa = fa | FileAttributes.ReadOnly;

            }

            if ((fa & FileAttributes.Hidden) == FileAttributes.Hidden)

            {

                //如果有隐藏属性,而设置取消隐藏,那么使用异或方式

                if (checkBox2.Checked == false)

                    fa = fa ^ FileAttributes.Hidden;

            }

            else

            {

                //如果没有隐藏属性,而设置隐藏,那么使用或方式

                if (checkBox2.Checked == true)

                    fa = fa | FileAttributes.Hidden;

            }

            if ((fa & FileAttributes.System) == FileAttributes.System)

            {

                //如果有系统属性,而设置取消系统,那么使用异或方式

                if (checkBox3.Checked == false)

                    fa = fa ^ FileAttributes.System;

            }

            else

            {

                //如果没有系统属性,而设置系统,那么使用或方式

                if (checkBox3.Checked == true)

                    fa = fa | FileAttributes.System;

            }

            //目录设置新属性

            di.Attributes = fa;

        }

运行结果如下图所示:

图10-4 设置目录属性并使用attrib命令验证

10.2.1.4 目录的创建、删除和移动

目录的创建、删除和移动分别使用到了DirectoryInfo类的Create、Delete和MoveTo方法。

【例 10.5【项目:code10-005】目录的创建、删除和移动。

        //获得源目录路径

        private void button1_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            label1.Text = fbd.SelectedPath;

        }

        //获得目标目录路径

        private void button2_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            label2.Text = fbd.SelectedPath;

        }

        //在源目录下创建一个子目录 csharp

        private void button3_Click(object sender, EventArgs e)

        {

            if (label1.Text == "")

                return;

            string newFolder = label1.Text.Substring(label1.Text.Length - 1, 1) == "\\" ?

                label1.Text.Substring(0, label1.Text.Length - 1) :

                label1.Text;

            DirectoryInfo di = new DirectoryInfo(newFolder + "\\csharp");

            if(di.Exists )

            {

                MessageBox.Show("目录已经存在,不能创建该目录。", "错误信息");

                return;

            }

            di.Create();

            MessageBox.Show("目录创建成功。", "提示信息");

        }

        //删除源目录

        private void button4_Click(object sender, EventArgs e)

        {

            if (label1.Text == "")

                return;

            DirectoryInfo di = new DirectoryInfo(label1.Text );

            if (di.Parent == null)

            {

                MessageBox.Show("为确保文件安全,不允许删除根目录", "错误信息");

                return;

            }

            if(di.Exists )

            {

                try

                {

                    if (MessageBox.Show("确实要删除此目录?", "警告信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)

                        return;

                    di.Delete(true);

                    MessageBox.Show("目录已经成功删除。", "提示信息");

                }

                catch(Exception ex)

                {

                    MessageBox.Show("删除目录时发生错误:" + ex.Message, "错误信息");

                }

            }

            else

            {

                MessageBox.Show("目录不存在。", "错误信息");

            }

        }

        //移动源目录到目标目录,注意:必须在同一分区下移动

        private void button5_Click(object sender, EventArgs e)

        {

            if (label1.Text == "" | label2.Text == "")

                return;

            DirectoryInfo di = new DirectoryInfo(label1.Text);

            string toFolder;

            toFolder = label2.Text.Substring(label2.Text.Length - 1, 1) == "\\" ? label2.Text : label2.Text + "\\";

            toFolder = toFolder + di.Name;

            if(di.Exists)

            {

                try

                {

                    di.MoveTo(toFolder);

                    MessageBox.Show("目录移动完成。", "提示信息");

                }

                catch(Exception ex)

                {

                    MessageBox.Show("移动目录时发生错误:"+ ex.Message, "错误信息");

                }

            }

            else

            {

                MessageBox.Show("目录不存在。", "错误信息");

            }

        }

运行结果如下图所示:

图10-5目录的创建、删除和移动

10.2.2 Directory类

除了DirictoryInfo类外,VB.Net还提供了Directory类来操作目录、获得目录信息。

Directory类与DirectoryInfo类相比,Directory没有属性,提供的方法都是静态方法,可以直接使用;而DirectoryInfo的方法需要类实例化后使用。

其实DirectoryInfo的一些方法甚至就是调用Directory对应的方法。

Directory常用方法:

  1. CreateDirectory:创建目录。
  2. Delete:删除目录。
  3. Move:移动目录。
  4. GetLogicalDrives:检索此计算机上格式为“<驱动器号>:\”的逻辑驱动器的名称,这是一个字符串数组。
  5. GetDirectories:子目录的名称(包括其路径),这是一个字符串数组。
  6. GetFiles:目录中文件的名称(包括其路径),这是一个字符串数组。
  7. GetCreationTime:获得目录创建时间。
  8. GetLastWriteTime:获得目录最后修改时间。
  9. GetLastAccessTime:获得目录最后访问时间。
  10. GetParent:获得父目录,这是一个DirectoryInfo类型。
  11. SetCreationTime:设置目录创建时间。
  12. SetLastWriteTime:设置目录最后修改时间。
  13. SetLastAccessTime:设置目录最后访问时间。
  14. GetCurrentDirecotry:获得程序所在路径。
  15. Exists:目录是否存在。
10.2.2.1 获取目录信息

【例 10.6【项目:code10-006】获取某个目录的信息。

        private void button1_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.ShowNewFolderButton = false;

            if (fbd.ShowDialog() !=DialogResult.OK)

                return;

            string folderPath = fbd.SelectedPath;

            textBox1.Text += "路径:" + folderPath + "\r\n";

            textBox1.Text += "根目录:" + Directory.GetDirectoryRoot(folderPath) + "\r\n";

            if (Directory.GetParent(folderPath)!=null)

                textBox1.Text += "父目录:" + Directory.GetParent(folderPath).FullName + "\r\n";           

            textBox1.Text += "创建日期:" + Directory.GetCreationTime(folderPath).ToString("yyyy-MM-dd") + "\r\n";

            textBox1.Text += "最后修改日期:" + Directory.GetLastWriteTime(folderPath).ToString("yyyy-MM-dd") + "\r\n";

            textBox1.Text += "最后访问日期:" + Directory.GetLastAccessTime(folderPath).ToString("yyyy-MM-dd");

        }

运行结果如下图所示:

图10-6 获取目录信息

10.2.2.2 获取子目录和文件

获取当前目录的子目录和所有文件主要是使用GetDirectories和GetFiles方法,这两个方法不同于DirectoryInfo类提供的方法,它们返回的是包含的子目录和文件的全路径的字符串数组。

【例 10.7【项目:code10-007】获得子目录和文件。

         private void button1_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            listBox1.Items.Clear();

            string selPath = fbd.SelectedPath;

            //遍历所有的子目录

            foreach ( string subdirectory in Directory.GetDirectories(selPath))

            {

                listBox1.Items.Add("目录" + subdirectory);

            }

            //遍历所有的文件

            foreach (string file in Directory.GetFiles(selPath))

            {

                listBox1.Items.Add("文件" + file);

            }

        }

运行结果同【例 10.3】。

10.2.2.3 目录的创建、删除和移动

目录的创建、删除和移动分别使用到了Directory类的CreateDirectory、Delete和Move方法。

【例 10.8【项目:code10-008】目录的创建、删除和移动。

        //获得源目录路径

        private void button1_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            label1.Text = fbd.SelectedPath;

        }

        //获得目标目录路径

        private void button2_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)

                return;

            label2.Text = fbd.SelectedPath;

        }

        //在源目录下创建一个子目录 csharp

        private void button3_Click(object sender, EventArgs e)

        {

            string newFolder = label1.Text.Substring(label1.Text.Length - 1, 1) == "\\" ? label1.Text.Substring(0, label1.Text.Length - 1) : label1.Text;

            newFolder += "\\csharp";

            if (Directory.Exists(newFolder))

            {

                MessageBox.Show("目录已经存在,不能创建该目录。", "错误信息");

                return;

            }

            Directory.CreateDirectory(newFolder);

            MessageBox.Show("目录创建成功。", "提示信息");

        }

        //删除源目录

        private void button4_Click(object sender, EventArgs e)

        {

            if (label1.Text == "")

                return;

            string folder = label1.Text;

            if (Directory.GetParent(folder) == null)

                MessageBox.Show("为确保文件安全,不允许删除根目录", "错误信息");

                return;

            if(Directory.Exists (folder))

            {

                try

                {

                    if (MessageBox.Show("确实要删除此目录?", "警告信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)

                        return;

                    //调用Delete方法删除,参数True表示要删除该目录中的子目录和文件

                    Directory.Delete(folder, true);

                    //如果使用不带参数的方法只能是删除空目录

                    Directory.Delete(folder);

                    MessageBox.Show("目录已经成功删除。", "提示信息");

                }

                catch(Exception ex)

                {

                    MessageBox.Show("删除目录时发生错误:" + ex.Message, "错误信息");

                }

            }

            else

            {

                MessageBox.Show("目录不存在。", "错误信息");

            }

        }

         //移动源目录到目标目录

         //注意必须在同一分区下移动

        private void button5_Click(object sender, EventArgs e)

        {

            if (label1.Text == "" | label2.Text == "")

                return;

            DirectoryInfo di = new DirectoryInfo(label1.Text);

            string toFolder = label2.Text.Substring(label2.Text.Length - 1, 1) == "\\" ? label2.Text : label2.Text + "\\";

            toFolder += di.Name;

            if(Directory.Exists(label1.Text))

            {

                try

                {

                    //调用MoveTo方法移动

                    Directory.Move(label1.Text, toFolder);

                    MessageBox.Show("目录移动完成。", "提示信息");

                }

                catch (Exception ex)

                {

                    MessageBox.Show("移动目录时发生错误:" + ex.Message, "错误信息");

                }

            }

            else

            {

                MessageBox.Show("目录不存在。", "错误信息");

            }

        }

运行结果同【例 10.5】。

学习更多vb.net知识,请参看vb.net 教程 目录

学习更多C#知识,请参看C#教程 目录

http://www.lryc.cn/news/528642.html

相关文章:

  • LiteFlow Spring boot使用方式
  • OSCP:Windows 服务提权详解
  • 星火大模型接入及文本生成HTTP流式、非流式接口(JAVA)
  • 21.Word:小赵-毕业论文排版❗【39】
  • Python中的函数(上)
  • Windows11 安装poetry
  • 浅谈Linux 权限、压缩、进程与服务
  • 006 LocalStorage和SessionStorage
  • AJAX RSS Reader:技术解析与应用场景
  • Go优雅实现redis分布式锁
  • 本地部署deepseek模型步骤
  • (2025 年最新)MacOS Redis Desktop Manager中文版下载,附详细图文
  • C++ 写一个简单的加减法计算器
  • 计算机网络基础 - 链路层(3)
  • ray.rllib 入门实践-5: 训练算法
  • FPGA 使用 CLOCK_LOW_FANOUT 约束
  • 选择的阶段性质疑
  • 固有频率与模态分析
  • 数科OFD证照生成原理剖析与平替方案实现
  • CAN总线数据采集与分析
  • SpringSecurity:There is no PasswordEncoder mapped for the id “null“
  • ResNet 残差网络
  • CAPL编程常见问题与解决方案深度解析
  • 信号处理以及队列
  • Linux pkill 命令使用详解
  • react注意事项
  • 【开源免费】基于SpringBoot+Vue.JS在线考试学习交流网页平台(JAVA毕业设计)
  • 怎样在PPT中启用演讲者视图功能?
  • UE AController
  • H264原始码流格式分析