C# 文件操作系列一

时间:2022-04-24
本文章向大家介绍C# 文件操作系列一,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在.Net环境中,所有关于文件操作的类都在System.IO命名空间下,注:在修改文件时,安全性显得格外重要,但是本随笔不过多讲述安全性,这里假设我们有足够的权限。

1、管理文件系统

先通过一幅图来了解整个文件系统的关键类

(1)、System.MarshalByRefObject类:这是.Net类中用于远程操作的基对象类,它允许在应用程序域之间编组数据.

(2)、FileSystemInfo类:这是任何文件系统对象的基类

(3)、Path类:这个类包含的静态成员可以用于处理路径名

(4)、DriveInfo类:它的属性和方法提供了指定驱动器的信息

(5)、Directory和DirectoryInfo类:这些类表示文件系统上的文件夹

(6)、FileInfo和File类:这些类表示文件系统上的文件

上图中有两个表示文件夹的类,两个表示文件的类,具体用哪个类取决于访问文件夹和文件的次数。

(7)、Directory类和File类与DirectoryInfo和FileInfo类的区别

Directory类和File类这两个类是静态类,所以不能实例化,如果只对文件或者文件夹执行一个操作,使用这两个类就很好,因为能省去实例化的开销。

DirectoryInfo和FileInfo类实现与Directory类和File类大致相同的公共方法,并拥有一些公共属性和构造函数,但它们都是有状态的,且这些类的成员都不是静态的。需要实例化这些类。如果一个对象执行多个操作,那么使用这两个类就比较方便。因为在构造时,将读取合适文件系统对象的身份和其他的一些信息,无论对象(类实例)调用了多少方法,都不需要再次读取这些信息。相比之下.Directory类和File类两个无状态类则需要再次读取相应的文件系统的信息。

(8)File类与FileInfo类的区别

下面通过简单的复制文件,来比较两者的区别,代码如下:

FileInfo类

Stopwatch sw = new Stopwatch();
sw.Start();
FileInfo info = new FileInfo(@"C:UsersAdministratorDesktopprojectMVCC#高级编程(第9版):C#5.0 & .NET 4.5.1_13698151.pdf");
info.CopyTo(@"C:UsersAdministratorDesktopTestC#高级编程(第9版):C#5.0 & .NET 4.5.1_13698151.pdf",true);
sw.Stop();
TimeSpan ts = sw.Elapsed;
string Elapsed = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
Console.WriteLine("The total running hours is {0}", Elapsed);
Console.ReadLine();

File类

Stopwatch sw = new Stopwatch();
sw.Start();
File.Copy(@"C:UsersAdministratorDesktopprojectMVCC#高级编程(第9版):C#5.0 & .NET 4.5.1_13698151.pdf", @"C:UsersAdministratorDesktopTestC#高级编程(第9版):C#5.0 & .NET 4.5.1_13698151.pdf", true);
sw.Stop();
TimeSpan ts = sw.Elapsed;
string Elapsed = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
Console.WriteLine("The total running hours is {0}", Elapsed);
Console.ReadLine();

如果不知道Stopwatch类的用法请参考Stopwatch类学习

通过上面的代码实例发现使用静态类File程序执行的时间更少,因为系统省去了实例化的实例化的时间

(9)Exists属性

该属性FileInfo和DirectoryInfo都实现了,该属性用于判断文件和文件夹是否存在,如果传入的路径表示一个不存在的对象,当通过FileInfo和DirectoryInfo初始化一个对象时都会传递一个路径,通过这种方法构造时并不会抛出异常,但是第一次调用方法时就会抛出异常,所以这种情况下,通过Exists属性来检查文件和文件夹是否存在是十分必要的,如果通过Exists属性接茬通过之后,就可以查看当前实例的其他属性,具体的属性如下:

注:创建时间和最后一次访问时间、最后一次写入时间都是可写入的。

除了查看属性之外,还可以对文件系统对象执行操作,具体的操作列表如下:

    上面只是一部分常用的操作,并不是FileInfo和DirectoryInfo实例所有的方法和属性。读写文件实际上是使用流对象完成,FileInfo也可以实现Open()、OpenRead()、OpenWrite()、OpenText()、Create()、CreateText()等操作,为此他们返回的都是流对象。

(10)、Path类是一个静态类,该类不能实例化,它提供了一些静态方法,可以更容易的对路径名进行操作,比如说Combine方法就支持若干个路劲的合并,使用Path类要比手动处理各个符号要容易的多,特别是Path类能处理不同操作系统上的路径名,虽然.Net只支持Windows平台。下面是Path类的部分属性和方法

下面通过一个窗体应用程序,来展示关于文件的操作,以下是操作界面:                         点击下载源码

文件移动:

        /// <summary>
        /// 文件移动
        /// </summary>
        protected void FileMove()
        {
            try
            {
                string filepath = Path.Combine(_currentDirectory, textBox2.Text);
                string query = "Really move the filen" + filepath + "n to" + textBox8.Text + "?";
                if (MessageBox.Show(query, "Move File?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    File.Move(filepath, textBox8.Text);
                    DisplayFolderList(_currentDirectory);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to move file.The follow exception" + "occured:n" + ex.Message, "Failed");
            }
        }

文件复制:

        protected void FileCopy()
        {
            try
            {
                string filepath = Path.Combine(_currentDirectory, textBox2.Text);
                string query = "Really copy the filen" + filepath + "n to " + textBox8.Text + "?";
                if (MessageBox.Show(query, "Copy File?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    File.Copy(filepath, textBox8.Text);
                    DisplayFolderList(_currentDirectory);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to copy file.The follow exception" + "occured:n" + ex.Message, "Failed");
            }
        }    

文件删除:

        protected void FileDelete()
        {
            try
            {
                string filepath = Path.Combine(_currentDirectory, textBox2.Text);
                string query = "Really delete the filen" + filepath + "?";
                if (MessageBox.Show(query, "Delete File?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    File.Delete(filepath);
                    DisplayFolderList(_currentDirectory);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to delete file.The follow exception" + "occured:n" + ex.Message, "Failed");
            }
        }

展示文件信息:

        /// <summary>
        /// 展示文件信息
        /// </summary>
        /// <param name="path">文件路径</param>
        protected void DisplayFileInfo(string path)
        {
            
            if (path.Equals(string.Empty))
            {
                MessageBox.Show("请输入文件的路径!");
                return;
            }
            FileInfo info = new FileInfo(path);
            if (!info.Exists)
            {
                throw new FileNotFoundException("File Not Found" + path);
            }
            else
            {
                textBox2.Text = info.Name;
                textBox3.Text = info.Length.ToString() + "bytes";
                textBox4.Text = info.CreationTime.ToLongDateString();
                textBox5.Text = info.LastWriteTime.ToLongDateString();
                textBox6.Text = info.LastAccessTime.ToLongDateString();
            }
        }

显示目标文件夹的所有信息:

        protected void DisplayFolderList(string path)
        {
            DirectoryInfo info = new DirectoryInfo(path);
            if (path.Equals(string.Empty))
            {
                MessageBox.Show("请输入文件夹的路径!");
                return;
            }
            if (!info.Exists)
            {
                throw new FileNotFoundException("File Not Found" + path);
            }
            else
            {
                Clear();
                textBox7.Text = info.FullName;
                _currentDirectory = info.FullName;
                foreach (var innerFolder in info.GetDirectories())
                {
                    listBox2.Items.Add(innerFolder.Name);
                }
                foreach (var file in info.GetFiles())
                {
                    listBox1.Items.Add(file.Name);
                }
            }
        }