public class FileFunction
{
public static void SaveToTxT(string strPath, string strData)
{
using (FileStream fsWrite = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] buffer = Encoding.Default.GetBytes(strData);
fsWrite.Position = fsWrite.Length;
fsWrite.Write(buffer, 0, buffer.Length);
fsWrite.Close();
}
}
public static string LoadByTxT(string strPath)
{
string strRead = "";
using(FileStream fsRead = new FileStream(strPath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fsRead.Length];
fsRead.Position = 0;
fsRead.Read(buffer, 0, buffer.Length);
strRead = Encoding.Default.GetString(buffer);
fsRead.Close();
}
return strRead;
}
}
写:将string类型的数据通过默认的编码器转为byte数组,再通过文件流写入txt文件。
读:先通过文件流打开文件,再将其读入byte数组,之后采用默认编码器转化为string类型数据。