C#学习笔记——(23)文件

文本文件的读写

文件是记录在外部介质上的数据的集合。Visual Studio中与文件操作有关的类在命名空间System.IO中,因此在程序的开头需要引入这个命名空间。
在这里插入图片描述
在这里插入图片描述

读写文件
  • 引入名字空间
using System.IO;
  • 写文件用StreamWriter方法
StreamWriter swFile = new StreamWriter("C:\\MyFile.txt");
StreamWriter swFile = new StreamWriter("C:\\MyFile.txt",True);

常用方法
Write方法:调用StreamWriter对象的Write方法,可以往文件中写入一个字符串。
WriteLine方法:调用StreamWriter的WriteLine方法,可以往文件中写入一个字符串和一个换行符(写入一行)。
Close方法:释放StreamWriter对象,并关闭打开的文件。
例子

StreamWriter swFile = new StreamWriter("C:\\MyFile.txt");
swFile.WriteLine("君为女萝草,妾作菟丝花。");
swFile.WriteLine("轻条不自引,为逐东风斜。");
swFile.Close();
  • 读文件用StreamReader方法

常用方法
Read 方法:从文件(流)中读入下一个字符
ReadLine方法:从文件(流)中读入下一行字符
Close方法:关闭打开的文件(流)
ReadToEnd方法:从文件(流)的当前位置读到文件(流)的结尾
Peek方法:返回文件(流)中的下一个字符,但并不读入该字符

StreamReader srFile =new StreamReader("C:\\MyFile.txt");
String strIn;
While(srFile.Peek()>-1)
{
   strIn += srFile.ReadLine();
}
读写二进制文件
  • FileStream对象-打开或创建文件(只提供了字节的写入方式)

构造函数

//path用于指定要打开或创建文件的路径及文件名
//mode用于指定文件打开的模式,可以是Creat(创建)Open(打开)等
//access用于指定文件访问的目的,可以是Read(读)Write(写)和ReadWrite(读写)
public FileStream(String path,FileMode mode,FileAccess access);

常用方法
Read和Write方法:对文件进行读写

//array Byte型数组,存放准备写入文件流的数据,或是从文件流中读出的数据
//offset准备从数组中向文件写入或读出的数据在数组中的偏移量
//count写入或读出的最大字节数
override int Read(unsigned char[] array,int offset,int count);

ReadByte和WriteByte方法:一次向文件流中读出或写入一个字节

override void WriteByte(Byte value);
override int ReadByte();

Close方法:关闭或打开文件
Seek方法:在文件流中定位

//offset指定相对于origin的移动偏移量
//origin指定指针移动方向,可以有三种选择
Begin从文件头往后开始移动指针
Current从文件的当前位置往后开始移动指针
End从文件尾往前开始移动指针
override long Seek(long offset,SeekOrigin origin);
  • BinaryWriter和BinaryReader对象(二进制写类和二进制写类)

在构造了FileStream对象后可以将该对象进一步构造为BinaryWriter和BinaryReader对象,以获取更高级的功能。需要从一个存在的流来构造BinaryWriter和BinaryReader对象,例如:

FileStream fsRW = new FileStream("E:\\MyFile.bin",FileMode.Open,FileAccess.Read);
BinaryWriter bwMyFile = new(fsRW);

BinaryWriter写入方法
void Write(Boolean):将1字节Boolean值写入当前流
void Write(Byte):将一个无符号字节写入当前流
void Write(Char()): 将字符数组写入当前流
void Write(Decimal):将一个十进制数值写入当前流
void Write(Double):将8字节浮点值写入当前流
void Write(Short):将2字节有符号整数写入当前流
void Write(Integer):将4字节有符号整数写入当前流
void Write(Long):将8字节有符号整数写入当前流

BinaryReader读入方法
ReadBoolean:从当前流中读取 Boolean
ReadByte:从当前流中读取下一个字节
ReadBytes:从当前流中将 count个字节读入字节数组
ReadChar:从当前流中读取下一个字符
ReadDecimal;从当前流中读取十进制数值
ReadDouble:从当前流中读取8字节浮点值
ReadSingle:从当前流中读取4字节浮点值
ReadString:从当前流中读取一个字符串。字符串有长度前缀,一次7位地被编码为整数。

序列化对象

序列化对象表示为字节序列,包括对象数据和关于对象类型及对象中所存放数据类型的信息。序列化对象写入文件后,可以从文件读取并去序列化,即用对象类型及对象中所存放数据类型的信息在内存中重建对象。
方法
BinaryFormatter类:可以读取和写入流中的整个对象。Serialize将对象表示写入文件(序列化),Deserialize读取这个表示并重建对象(去序列化)。

文件和目录的操作

目录操作
Directory类

主要是Directory类,提供了操作一个目录所需要的大部分方法,Directory类中的方法全部是静态的,因此无需生成Directory的实例便可使用这种方法。
常用的方法

  • CreateDirectory(string Path):该方法按照Path所指定的路径创建一个新的目录。如果Path指定的路径格式不对,或者不存在等错误均会引发异常。最好将该方法置于try语句中。
  • Delete(string Path, bool recursive):该方法删除Path所指定的目录。如果recursive为false,则仅当目录为空时删除改目录。若为true,则删除目录下的所有子目录和文件。
  • Exists(string Path):该方法测试Path所指定的目录是否存在。若存在,则返回true。反之返回false。
  • GetDirectories(string Path):该方法得到Path所指定的目录中包含的所有子目录。结果已字符串数组的形式返回,数组中的每一项对应一个子目录。
  • GetFiles(string Path):该方法和GetDirectories方法类似,返回目录中所有的文件名。
  • Move( string sourceDirName,string destDirName):该方法将一个目录中的内容移动到一个新的位置。sourceDirName指定要移动的目录,destDirName指定移动到何处。
  • GetLogicalDrives():返回计算机中的所有逻辑驱动器名称。
  • Copy(string sourceFileName,string destFileName):sourceFileName指出要复制文件的文件名以及该文件的路径,destFileName指出新的副本的文件名可以带有路径。但destFileName不能是一个目录或者一个以存在的文件。
  • Delete(string path):删除一个文件。path指出该文件名和路径。
  • Exists(string path):As Boolean测试path指定的文件是否存在。若是,返回true,否则返回false。
  • Move(string sourceFileName,string destFileName):将文件由位置sourceFileName处移动到新位置destFileName处。
  • GetCreationTime(string path As String):返回由path所指定文件的创建日期和时间。类似的还
  • GetLastAccessTime,返回上次访问指定文件的日期和时间。GetLastWriteTime返回上次写入指定文件或目录的日期和时间。
Path类

对文件的路径进行修改
常用方法

  • ChangeExtension:更改路径字符串的扩展名。
  • Combine(String[]):将字符串数组组合成一个路径。
  • GetDirectoryName:返回指定路径字符串的目录信息。
  • GetExtension:返回指定的路径字符串的扩展名。
  • GetFileName:返回指定路径字符串的文件名和扩展名。
  • GetFileNameWithoutExtension:返回不具有扩展名的指定路径字符串的文件名。
  • GetFullPath:返回指定路径字符串的绝对路径。
  • GetTempFileName:创建磁盘上唯一命名的零字节的临时文件,并返回该文件的完整路径。
  • GetTempPath:返回当前用户的临时文件夹的路径。

例题-写入读取文本文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;              //首先需要添加IO的库,才能够读写文件

namespace TextFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonWrite_Click(object sender, EventArgs e)     //写入
        {
            SaveFileDialog sfDialog = new SaveFileDialog();
            sfDialog.Filter = "TEXT|*.txt";     //过滤器,只能存txt格式的文件
            string fileName;
            if(sfDialog.ShowDialog()==DialogResult.OK)  //当按键按下时
            {
                fileName = sfDialog.FileName;
                StreamWriter stWriter = new StreamWriter(fileName);   //用户选择的名字通过构造函数打开
                stWriter.Write(textBox1.Text);   //存入的文字为文本框内的文字
                stWriter.WriteLine("");
                stWriter.Close();  //最后要关闭文件才能保存
            }
        }

        private void buttonRead_Click(object sender, EventArgs e)   //读出
        {
            OpenFileDialog ofDialog = new OpenFileDialog();
            ofDialog.Filter = "TEXT|*.txt";
            if(ofDialog.ShowDialog()== DialogResult.OK)
            {
                StreamReader stReader = new StreamReader(ofDialog.FileName);
                textBox1.Text = stReader.ReadToEnd();
                stReader.Close();
            }
        }
    }
}

例题-读写二进制文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;              //首先需要添加IO的库,才能够读写文件

namespace TextFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonWrite_Click(object sender, EventArgs e)     //写入
        {
            SaveFileDialog saDialog = new SaveFileDialog();
            if (saDialog.ShowDialog() == DialogResult.OK)
            {
                //构造FileStream对象
                FileStream fs = new FileStream(saDialog.FileName, FileMode.Create, FileAccess.Write);
                //需要从一个存在的流来构造BinaryWriter和BinaryReader对象
                BinaryWriter bw = new BinaryWriter(fs);
                var firstInt = Convert.ToInt32(textBox1.Text);
                var secondDouble = Convert.ToDouble(textBox3.Text);
                bw.Write(firstInt);
                bw.Write(secondDouble);
                bw.Write(textBox2.Text);
                bw.Close();
            }
        }
        private void buttonRead_Click(object sender, EventArgs e)   //读出
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(op.FileName, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                var firstInt = br.ReadInt32();
                var secondDouble = br.ReadDouble();
                var str = br.ReadString();
                textBox1.Text = firstInt.ToString();
                textBox3.Text = secondDouble.ToString();
                textBox2.Text = str;
                br.Close();
                fs.Close();
            }
        }
    }
}

例题-序列化和去序列化

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;   //
using System.Runtime.Serialization.Formatters.Binary;   //二进制时需要加该库

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        MyData mydata = new MyData();  //创建class类的实例
        private void buttonwrite_Click(object sender, EventArgs e)
        {
            mydata.first = Convert.ToInt32(textBox1.Text);
            mydata.second = Convert.ToDouble(textBox2.Text);
            mydata.str = textBox3.Text;
            //创建文件流
            FileStream fs = new FileStream("d:\\mydata.da",FileMode.Create,FileAccess.Write);
            //二进制格式化流
            BinaryFormatter bf = new BinaryFormatter();
            //调用序列化函数
            bf.Serialize(fs, mydata);
            fs.Close();
        }

        private void buttonread_Click(object sender, EventArgs e)
        {
            MyData mydata2 = new WindowsFormsApplication2.MyData();
            FileStream fs = new FileStream("d:\\mydata.da", FileMode.Open, FileAccess.Read);
            BinaryFormatter bf = new BinaryFormatter();
            //去序列化
            mydata2 = (MyData)bf.Deserialize(fs);
            //显示到文本框中
            textBox1.Text = mydata2.first.ToString();
            textBox2.Text = mydata2.second.ToString();
            textBox3.Text = mydata2.str;
            fs.Close();
        }
    }
    //标记这个类是可序列化的,读写要按一定的顺序
    [Serializable]
    public class MyData   //将整个class作为对象存到磁盘上,是可序列化的
    {
        public int first;
        public double second;
        public string str;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值