C#基础——文件、文件夹操作和序列化存储

文件操作、文件夹操作和序列化存储

1、文件操作

如果要对文件进行操作,首先需要先引入IO命名空间

using System.IO;

File 类位于 System.IO 命名空间中,用于执行文件级别的操作。它提供了一组静态方法,用于创建、复制、删除、移动和读取文件内容等操作。

文件操作的核心是文件路径

// @ 表示后续是一个原始字符串
// D 表示电脑的盘符
// \ 代表下一层
// myfile.txt
string filePath = @"D:\cSharp\myfile.txt"; //声明一个文件路径

Create 创建文件

File.Create("D:\cSharp\myfile.txt");

WriteAllText 创建一个新文件并写入内容,如果文件存在,则会被覆盖

string filePath =  @"D:\cSharp\myfile.txt"; //创建一个文件路径
string content = "Hello, this is some content。";

// 创建一个新文件并写入内容
File.WriteAllText(filePath, content);

WriteAllLines 创建文件写入指定数组然后关闭该文件

string[] contentArray = { "张三", "李四", "王五", "赵六", "陈七" }; //创建一个数组
File.WriteAllLines("D:\cSharp\yofile.txt", contentArray);

ReadAllText 读取文件内容

string textContent = File.ReadAllText("D:\cSharp\myfile.txt");
Console.WriteLine(textContent) //Hello, this is some content。

AppendAllText 追加内容到文件

//第一个参数是文件地址,第二个参数是需要添加的内容
File.AppendAllText("D:\cSharp\myfile.txt", "Content to append");

Copy 复制文件

//第一个参数是需要复制的文件地址,第二个参数是新的文件地址
File.Copy("D:\cSharp\myfile.txt", "D:\cSharp\yofile.txt");

Move 移动文件

//第一个参数是需要移动的文件,第二个参数是新的文件地址
File.Move("D:\cSharp\myfile.txt", "E:\cSharp\yofile\youfile.txt");

Delete 删除文件

File.Delete("D:\cSharp\yofile.txt");

Exists 判断文件是否存在

File.Exists("D:\cSharp\yofile.txt"); //返回一个布尔值

StreamReader:实现一个可读取有序字符系列的读取器,使其以一种特定的编码从字节流中读取字符。

string path = @"D:\CSharp课件\test.txt";
//根据路径实例化读取对象
StreamReader sr = new StreamReader(path);
//ReadToEnd 获取到当前流中读取到的内容
Console.WriteLine(sr.ReadToEnd());
//因为属于流操作,所以使用完毕之后最好是关闭,节省资源
//Close 关闭流
sr.Close();

StreamWriter:实现一个编写一个有序字符系列的编写器,使其以一种特定的编码向流中写入字符。

 string namePath = @"D:\CSharp课件\test.txt";
 //如果路径下没有该文件,则会先创建文件,在写入
 StreamWriter streamWriter = new StreamWriter(namePath);
 //写入内容
 streamWriter.Write("关注");
 streamWriter.Write("郭贝贝同学");
 streamWriter.WriteLine("博主");
 streamWriter.WriteLine("一起");
 streamWriter.WriteLine("学习");
 streamWriter.WriteLine("编程");

 //使用循环把List写入到文件中
 List<int> ints = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 foreach (int i in ints) {
   streamWriter.WriteLine(i);
 }
//Close 关闭流
 streamWriter.Close();

FileStream:为文件提供字节序列的一般视图,既支持同步读写操作,也支持异步读写操作。

StreamReader:实现一个可读取有序字符系列的读取器,使其以一种特定的编码从字节流中读取字符。

string dicPath = @"D:\CSharp\dic.txt";
if (!File.Exists(dicPath)) {
  //如果文件不存在
  //参一代表文件路径,参二代表文件创建的模式,参三代表文件操作权限
  FileStream fs = new FileStream(dicPath, FileMode.Create, FileAccess.Write);
  //fs中保存的是关于当前文件的配置信息
  StreamWriter sw = new StreamWriter(fs);
  sw.WriteLine("FileStream相比较单文件路径,优势明显");
  sw.Close();
  fs.Close();
} else {
  //存在则读取
  FileStream fs = new FileStream(dicPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  StreamWriter sw = new StreamWriter(fs);
  sw.WriteLine("存在则读取,不存在则创建");
  sw.Close();
  fs.Close();
  
  //追加内容
  //FileStream fs = new FileStream(dicPath, FileMode.Append, FileAccess.ReadWrite);
  //StreamWriter sw = new StreamWriter(fs);
  //sw.WriteLine("这是追加的内容");
  //sw.Close();
  //fs.Close();
};

2、文件夹操作

Directory:是一个用来操作文件夹的类

CreateDirectory 创建一个文件夹

string dicPath = @"D:\\CSharp课件\myDirectory"
string content = "这是myDirectort文件夹中的文件内容";
Directory.CreateDirectory(dataPath);

Exists 检测当前有没有文件夹

WriteAllText 创建一个新文件,写入内容,然后关闭该文件

if (Directory.Exists(dicPath)) {
  Directory.CreateDirectory(dicPath);
  //Path.Combine 路径合并
  string filePath = Path.Combine(dataPath, "data.txt");
  //WriteAllText 创建一个新文件,写入内容,然后关闭该文件
  //参数一是文件路径,参数二是要写入的内容
  //如果已有该文件,则覆盖该文件
  File.WriteAllText(filePath, content);
} else {
  string filePath = Path.Combine(dataPath, "data.txt");
  File.WriteAllText(filePath, content);
}

Delete 删除文件夹

Directory.Delete(dicPath);

3、序列化存储

如果直接对对象类型进行写入或读取操作,是没有办法获得想要的结果的。

如果想要把引用类型进行正确的读或者是写,需要先对引用类型进行序列化与反序列化操作才可以。

序列化存储:将对象转换为字节流或其他格式,以便在需要时能够重新构造出相同的对象。

序列化存储的目的:

  1. 持久化存储: 将对象转换为文件或数据库中的格式,使其在程序重新启动或在不同的系统之间传输时能够保持状态。
  2. 数据交换: 在不同系统或平台之间传输对象数据,序列化能够将对象转换为通用的数据格式,便于传输和解析。
// [Serializable] 添加可以序列化的特性,注意,如果不添加,那么该类不支持序列化。
[Serializable]
internal class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Student student = new Student()
{
    Name = "郭贝贝同学",
    Id = 18
};
//@"students.txt"在当前项目的debug目录下
FileStream fileStream = new FileStream(@"students.txt", FileMode.OpenOrCreate);
// BinaryFormatter 二进制格式化器
BinaryFormatter formatter = new BinaryFormatter();
//Serialize 将对象序列化到给定的流中
formatter.Serialize(fileStream, student);
fileStream.Close(); //关闭流

反序列化

//Deserialize 指定的流反序列化
//并将其转换为 Student 类型的对象
Student str = formatter.Deserialize(fileStream) as Student;
fileStream.Close();
Console.WriteLine("对象读取成功:"+str.Name); //郭贝贝同学
  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值