C# winform编程自学笔记(九) 文件处理技术-System.IO

C# winform编程自学笔记(九),上接(八)

内容一览

  1. System.IO类简介;
  2. File类 常用方法;
  3. FileInfo类 常用方法;
  4. Directory 文件夹类;
  5. File类 常用操作的静态方法练习;
  6. FileStream 文件流类。

——————正文——————

(一)System.IO类简介

以字节形式向磁盘写入的数据通常称为字节流;存储在磁盘上的字节集合称为文件
在Windows应用程序中,经常会读取文件中的数据,也会将数据存放到文件中去,这就是输入输出操作(I/O)

本章所有练习代码前面必须都加上 using System.IO;

对文件的读写操作在类库中,类库结构有一个System.IO命名空间。

1.System.IO命名空间常用的类

说明
File提供用于创建、复制、删除,移动和打开文件的静态方法,并协助创建FileStream对象
FileInfo提供用于创建、复制、删除、移动和打开文件的实例方法,并写出创建FileStream对象,无法继承此类
FileStream公开以文件为主的Stream,既支持同步读写操作,也支持异步读写操作
BinaryReader用特定的编码将基元数据类型读作二进制值
BinaryWriter以二进制形式将基元类写入流,并支持用特定的编码写入字符串
BufferedStream给另一流上的读写操作添加一个缓冲层,无法继承此类
Directory公开用于创建、移动和枚举目录和子目录的静态方法,无法继承此类
Directory公开用于创建、移动和枚举目录和子目录的实例方法,无法继承此类
Path对包含文件或目录路径信息的String实例执行操作,这些操作是以跨平台的方式执行的
StreamReader实现一个TextReader,使其以一种特定的编码从字节流汇总读取字符
StreamWriter实现一个TextWriter,使其以一种特定的编码向字节流中写入字符
FileSysWatcher侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件

2.头文件
using System.IO;

(二)File类 常用方法

利用MSDN(Microsoft Developer Network)就可以掌握File类的使用方法,File类提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建FileStream对象。

file有几个常用方法,如下:

方法说明
Move将指定文件移动到新位置,并提供指定新文件名的选项
Delete删除指定的文件,如果指定文件不存在,则不引发异常
Copy已重载。将现有文件复制到新文件
CreateText创建或打开一个文件用于写入UTF-8编码的文本
OpenText打开现有UTF-8编码文件以进行读取
Open已重载,打开指定路径上的FileStream

案例学习:
简单演示一些File类的主要方法:

//创建文件以便写入内容
StreamWtiter sw=File.CreateText("存储路径");
//写入内容
sw.WriteLine("hello world!");
//打开文件从中读取数据
using(StreamWriter sr=File.OpenText("存储路径");
{
	string s=" " ;
	while((s=sr.ReadLine())!=null)
	{
		Console.WriteLine(s);
		}
}
//删除文件
File.Delete("存储路径");
//复制文件
File.Copy("存储路径1","存储路径2");

(三)FileInfo类 常用方法

提供用于创建、复制、删除、移动和打开文件的实例方法,并写出创建FileStream对象,无法继承此类。

案例学习一:
本案例将解决同磁盘环境下文件复制的问题,如何编写将“路径1”文件复制到“路径2”下的代码呢?

1)向一个Form窗体上拖拽三个Button按钮,如图:
在这里插入图片描述
2)分别双击三个按钮,对其click事件处理方法如下:
【代码可运行,已经试验过了。但需要提前在path路径里做好被复制文件】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace UNIT3_1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        //创建文本文件
        private void button1_Click(object sender, EventArgs e)
        {
            string target = @"E:\\hello.txt";
            if(File.Exists(target))//验证文件是否存在
            {
                File.Delete(target);//删除该路径下的文件
            }
            File.CreateText(target);
            
            MessageBox.Show("文件创建成功", "信息提示");
        }

        //button2-复制文本文件
        private void button2_Click(object sender, EventArgs e)
        {
            string path = @"C:\2345Soft\filetest.txt";
            string target = @"E:\\hello.txt";
            FileInfo myfile = new FileInfo(path);
            if(!myfile.Exists)
            {
                MessageBox.Show("对不起,未发现路径文件!");
            }
            else
            {
                myfile.CopyTo(target);
                MessageBox.Show("复制成功");
            }
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string target = @"E:\\hello.txt";
            if(File.Exists(target))
            {
                File.Delete(target);
                MessageBox.Show("文件删除成功");
            }
        }
    }
}

案例学习二:
如何获取文件的创建日期、所在文件夹和文件夹名称。

1)向一个Form窗体上拖拽3个Label控件和一个Button控件,Button控件的text属性设置为“获取文件信息”,如图:
在这里插入图片描述

2)双击“获取文件信息”按钮,在click事件处理方法中分别添加代码如下:

记得在头文件中添加using System.IO;

 private void button1_Click(object sender, EventArgs e)
        {
            string somefile = @"C:\\2345Soft\testfile.txt";
            FileInfo myfile = new FileInfo(somefile);
            if(myfile.Exists)
            {
                MessageBox.Show("文件已经存在");
                label1.Text = "文件创建时间" + myfile.CreationTime.ToString();
                label2.Text = "文件夹:" + myfile.Directory.ToString();
                label3.Text = "文件夹名称" + myfile.DirectoryName.ToString();
            }
            else
            {
                MessageBox.Show("文件不存在");
            }
        }

实验结果:
在这里插入图片描述

(四)文件夹类 Diectory类的常用方法

方法说明
Move将文件或目录及其内容移动到新的位置
Delete已重载,删除指定的目录
CreateDirectory已重载,创建指定路径中的所有目录
GetCreationTime获取目录的创建日期和时间
GetCurrentDirectory获取应用程序的当前工作目录
GetFiles已重载,返回指定目录中的文件的名称

案例学习:

1)向一个Form窗体上拖拽五个Button,并进行如图设置:
在这里插入图片描述
2)对各按钮的编辑如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace UNIT3_1
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }


        private static string directory_path = "E:\\filetest.txt";
        private static string directory_otherpath = "E:\\hello.txt";
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Directory.CreateDirectory(directory_path);
                button2.Enabled = true;
                button1.Enabled = false;
                button3.Enabled = true;
                button4.Enabled = true;
                button5.Enabled = true;
                MessageBox.Show("文件夹成功建立", "警报");
            }
            catch(Exception mm)
            {
                MessageBox.Show("磁盘操作错误", "警报");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                Directory.CreateDirectory(directory_path);
                button2.Enabled = false;
                button1.Enabled = true;
                button3.Enabled = false;
                button4.Enabled = false;
                button5.Enabled = false;
                MessageBox.Show("文件夹成功建立", "警报");
            }
            catch (Exception mm)
            {
                MessageBox.Show("磁盘操作错误,原因:"+Convert.ToString(mm), "警报");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                Directory.Move(directory_path, directory_otherpath);
                
                MessageBox.Show("文件夹移动成功", "警报");
            }
            catch (Exception mm)
            {
                MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                MessageBox.Show(string.Format("{0:G}",Directory.GetCreationTime(directory_path ),"提示");
            }
            catch (Exception mm)
            {
                MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string[] fileEntries = Directory.GetFiles(directory_path);
                if(fileEntries.Length!=0)
                {
                    foreach(string s in fileEntries)
                    {
                        if(File.Exists(s))
                        {
                            MessageBox.Show("内有文件信息:" + s, "提示");
                        }
                    }
                }
            }
            catch (Exception mm)
            {
                MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
            }
        }

        private void Form4_Load(object sender, EventArgs e)
        {

        }
    }
}

实验结果:
在这里插入图片描述在这里插入图片描述

(五)File类的常用操作的静态方法练习

File类是一个静态类,不能被继承,它不仅提供一系列方法,用来针对文件的通用操作,还提供了一系列的读写文本文件的方法。

案例学习:

1)向一个Form窗体上拖拽两个GroupBox控件,设置如图,再向两个GroupBox控件里拖拽一个RichTextBox控件和一个TextBox控件;向第一个groupBox控件中拖拽两个Button控件;向第二个GroupBox控件中拖拽一个Button控件,如图所示:
在这里插入图片描述
2)对代码的设置如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace UNIT3_1
{
    public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
        }

        private static string directory_path = "E:\\";
       

        private void Form5_Load(object sender, EventArgs e)
        {

        }

        //保存编辑文件
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                FileStream textfile = File.Open(directory_path, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter sw = new StreamWriter(textfile,Encoding.GetEncoding("GB2312"));
                MessageBox.Show("文件写成功", "警报");
            }
            catch (Exception mm)
            {
                MessageBox.Show("文件未能建立" + Convert.ToString(mm), "消息");
            }
        }

        //创建文本文件
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if(textBox1.Text.Length==0)
                {
                    MessageBox.Show("文件名禁止为空!", "警报");
                }
                else
                {
                    directory_path = directory_path + textBox1.Text.Trim() + ".txt";
                    StreamWriter sw = File.CreateText(directory_path);
                    MessageBox.Show("文件成功建立", "消息");
                    sw.Close();
                }
            }
            catch(Exception mm)
            {
                MessageBox.Show("文件未能建立"+Convert.ToString(mm), "消息");
            }
        }

        //打开文本文件
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if(textBox1.Text.Length==0)
                {
                    MessageBox.Show("文件名禁止为空!", "警报");
                }
                else
                {
                    directory_path = directory_path + textBox1.Text.Trim() + ".txt";
                    StreamWriter sw = File.CreateText(directory_path);
                    MessageBox.Show("文件成功建立", "消息");
                    sw.Close();
                }
            }
            catch(Exception mm)
            {
                MessageBox.Show("文件未能建立" + Convert.ToString(mm), "消息");
            }
        }
    }
}

实验效果:
这个程序有个缺陷,就是必须先创建文件,然后才能保存文件。
在这里插入图片描述在这里插入图片描述

(六)文件流类FileStream

用File来创建或者打开文件的时候,总会产生一个FileStream对象,FileStream类是一个什么样的类?怎样通过它的对象来完成对文件的操作呢?

FileStream也叫文件流对象,为文件的读写提供通道。而File对象则相当于提供一个文件句柄,在文件操作中,针对FileStream对象的操作必须首先实例化一个FileStream类对象后才可以进行。

要构造FileStream对象,需要以下四个信息:
1)要访问的文件;
2)表示如何打开文件的模式,例如,创建一个新文件或者打开一个现有的文件;
3)表示访问文件的方式——只读,只写,还是读写?
4)共享访问——表示是否独占访问文件。

使用File对象的Create方法:
FileStream mikecatstream;
mikecatstream = File.Create(“路径”);

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值