说明:该功能可以用来创建日志,临时数据保存文件(本例创建的是txt格式)。
命名空间:using System.IO
利用对象:
/// <summary>
/// 文件流对象
/// </summary>
FileStream fsCodeList;
/// <summary>
/// 流读取对象
/// </summary>
StreamWriter swCodeList;
创建文件:
private void OpenOrCreateFile(string strPath)
{
//判断文件是否存在
if (!File.Exists(strPath))
{
//创建文件, 如果文件存在则打开,不存在则创建txt 文件
fsCodeList = new FileStream(strPath, FileMode.OpenOrCreate);
swCodeList = new StreamWriter(fsCodeList);
}
else
{
//文件存在则追加文本
fsCodeList = new FileStream(strPath, FileMode.Append);
swCodeList = new StreamWriter(fsCodeList);
}
}
private void DeleteUnlessFile(string strPath)
{
//获取当前文件目录
string path = Environment.CurrentDirectory;
string staPartten = "*.txt";
//读取当前文件目录下的所有的txt文件的文件名
string[] strArrFileName = Directory.GetFiles(path, staPartten);
foreach (string item in strArrFileName)
{
//文件不存在,删除
if (item != strPath)
File.Delete(item);
}
}
向文件中添加数据:在哪里需要添加数据就把这一行添加到哪里去
swCodeList.WriteLine("测试行数据");
关闭文件读写:不关闭会报错
swCodeList.Close();//先关闭读写对象
fsCodeList.Close();//后关闭文件流对象