Skip to content
字数
498 字
阅读时间
3 分钟

变量的本质是二进制,二进制读写文件的本质是:将各类型变量类型转换为字节数组=>将字节数组直接存储到文件中 C#提供公共类BitConverter(using System)帮助我们进行转化。(decimal和string不行)

cs
	bytes[] bytes = BitConverter.GetBytes(256);
	int i = BitConverter.ToInt32(字节数组, 从第x个索引开始);
	int i = BitConverter.ToInt32(bytes, 0);

怎么将字符串转码? 标准编码格式:用对应的二进制数,对应不同的文字。如果在读取字符时采用了不统一的编码格式,可能会出现乱码。 游戏开发中常用的编码格式 UTF-8 中文相关编码格式 GBK 英文相关编码格式 ASCII

C#编码格式类,帮助进行字符串和字节数组的转换:Encoding(using System.Text)

cs
	byte[] bytes2 = Encoding.UTF8.GetBytes("一个字符串")
	string s = Encoding.UTF8.GetString(bytes2);

文件相关操作

cs
	if(File.Exists(Application.dataPath + "/文件名")){}
	FileStream fs = File.Create(Application.dataPath +/文件名”)  //文件流类

将字节数组写入文件:

cs
	byte[] bytes = BitConverter.GetBytes(999);
	File.WriteAllBytes(Application.dataPath + "/文件名", bytes);

将字符串写入文件:

cs
	string[] strs = new stirng[]{"123", "随便什么字符串", "sfldkjs456"};
	File.WriteAllLines(Application.dataPath + "/文件名", strs);

将指定字符串写入指定路径:

cs
	File.WriteAllText(Application.dataPath + "/文件名", "换行测试\\n支持转义字符");

读取文件

cs
	//读取字节数据
	bytes = File.ReadAllBytes(Application.dataPath + "/文件名");
	//读取所有行信息
	strs = File.ReadAllLines(Application.dataPath + "/文件名");
	for(int i=0; i<strs.Length; i++){ print(strs[i]); }
	//读取所有文本信息
	print(File.ReadAllText(Application.dataPath + "/文件名"));

删除文件

cs
	File.Delete(Application.dataPath + "/文件名");

复制文件 //需要流关闭状态

cs
	File.Copy(Application.dataPath + "/原文件", Application.dataPath + "/克隆文件", true);

文件替换

cs
	File.Replace(用来替换的路径, 被替换的路径, 备份路径);

以流的形式 打开文件并写入或读取

cs
FileStream fs = File.Open(Application.dataPath + "/文件名", FileMode.OpenOrCreate, FileAccess.ReadWrite);

贡献者

The avatar of contributor named as worldddddd worldddddd

文件历史

撰写