建议先实现本文内容,然后扩展1,然后扩展2
1.写入文件
如果是在unity中,存储路径应该是Application.persistentDataPath+filename 还应进行加密
using System;
using System.Collections.Generic;
using System.Text;
using System.IO; // 注意添加这个头文件
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 存储路径和文件名
string filePath = "d:\\test.dat";
string[] data = new string[2];
data[0] = "为了部落";
data[1] = "为了联盟";
// 写
File.WriteAllLines(filePath, data);// 打开D盘查看是否写入成功
Console.WriteLine("按任意键继续。。。");
Console.ReadKey();
}
}
}
2.读取文件
前提上面保存在D盘的test.dat没有被删除
using System;
using System.Collections.Generic;
using System.Text;
using System.IO; // 注意添加这个头文件
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 存储路径和文件名
string filePath = "d:\\test.dat";
string[] data = new string[2];
// 判断文件是否存在
if (File.Exists(filePath))
{
// 读&存
data = File.ReadAllLines(filePath);
}
foreach (string str in data)
{
Console.WriteLine(str);
}
Console.WriteLine("按任意键继续。。。");
Console.ReadKey();
}
}
}
3.删除文件
using System;
using System.Collections.Generic;
using System.Text;
using System.IO; // 注意添加这个头文件
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 存储路径和文件名
string filePath = "d:\\test.dat";
// 判断文件是否存在
if (File.Exists(filePath))
{
File.Delete(filePath);
}
Console.WriteLine("按任意键继续。。。");
Console.ReadKey();
}
}
}
4.读写byte
服务器交互必备技能
using System;
using System.Collections.Generic;
using System.Text;
using System.IO; // 注意添加这个头文件
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 存储路径和文件名
string filePath = "d:\\test.dat";
// 要存储的信息
int data1 = 100;
float data2 = 0.5f;
// 记录字节位置信息
int index = 0;
byte[] bytes = new byte[128];
// 把data1转成byte
byte[] b = BitConverter.GetBytes(data1);
// 把data1存入上面申请的128位数组里
b.CopyTo(bytes, index);
// int为4字节,懂?
index += 4;
// 处理data2,同上
b = BitConverter.GetBytes(data2);
b.CopyTo(bytes, index);
index += 4;
// 写入
File.WriteAllBytes(filePath, bytes);
// test.dat是不是乱码?
// 别急继续
// 判断是否存在
if (File.Exists(filePath))
{
bytes = null;
// 读并存入bytes
bytes = File.ReadAllBytes(filePath);
// 转码 Int32 Single为.NET下的int和float
int readData1 = BitConverter.ToInt32(bytes, 0);// 从第0个字节开始取值
float readData2 = BitConverter.ToSingle(bytes, 4);// 从第4个字节开始取值
Console.WriteLine(readData1);
Console.WriteLine(readData2);
}
Console.WriteLine("按任意键继续。。。");
Console.ReadKey();
}
}
}