3.Winform初学之System.IO

System.IO命名空间中的常用类:

1>File:提供用于创建(Create)、复制(Copy)、删除(Delete)、移动(Move)和打开(Open)文件的静态方法,并协      助创建FileStream对象。
2>FileInfo:提供用于创建(Create)、复制(Copy)、删除(Delete)、移动(Move)和打开(Open)文件的实例方法,      并协助创建FileStream对象;此类无法被继承
3>FileStream:公开已文件的为主的Stream,支持同步、异步读写操作。
4>BinaryReader:用特定的编码将基元数据类型读作二进制值。

using System.IO 之File类:

//创建文件   :Create
        private void progressBar1_Click(object sender, EventArgs e)
        {
            string path = @"C:\123";//给定文件路径
            if( File.Exists(path))
            {
                MessageBox.Show("文件已存在!");
            }
            else
            {
                //StreamWriter:向流中写入字符
                using (StreamWriter sw = File.CreateText(path))//创建文件
                {
                    sw.WriteLine("123");
                    sw.WriteLine("456");
                }
            }

//打开、读取文件
            if ( !File.Exists(path) )
            {
                MessageBox.Show("文件不能为空!");
            }
            else
            {
                //StreamReader :从字节流中读取字符
                using (StreamReader sr = File.OpenText(path))
                {
                    Console.WriteLine(sr);
                }
            }
           //拷贝文件:Copy
            File.Copy(path2, path3);
            //移动文件:Move
            string path4 = @"C:\6330325";
            string path5 = @"C:\6339996";
            File.Move(path4, path5);
           //删除指定文件:Delete   
            File.Delete(path6);


System.IO之FileInfo类:


 //复制文件
private void progressBar1_Click(object sender, EventArgs e)
        {
            string path1 = @"C:\216161616";
            string path2 = @"C:\216161111";
            FileInfo newFileInfo = new FileInfo(path1);
            if( !newFileInfo.Exists)
            {
                MessageBox.Show("未发现路径文件");
            }
            else
            {
                //CopyTo:将文件复制
                newFileInfo.CopyTo(path2);
            }

                                                         《   其他属性类比File类  》


浅析File类与FileInfo类的区别:
1.File为静态类,可直接使用;FileInfo类需要实例化之后侧能使用;
2.如果要多次操作文件,无论是否针对相同文件,则应使用FileInfo类;
3.每次通过File类调用某个方法时,都要占用一次CPU,而FileInfo只需要占用一次;

你可能感兴趣的:(WinForm)