文件流读写

string FolderPath = "d:" + "//Logs";
//判断文件是否存在,否则创建;
if (Directory.Exists(FolderPath) == false)
{
Directory.CreateDirectory(FolderPath);
}

string year = DateTime.Now.Year.ToString().Trim();
string month = DateTime.Now.Month.ToString().Trim();
string day = DateTime.Now.Day.ToString().Trim();

string FilePath= FolderPath+"//log" +year + "-" + month + "-" + day + ".txt";
if (File.Exists(FilePath) == false)
{
//创建文件
FileStream fs123 = File.Create(FilePath);
fs123.Close();

}

//if (File.Exists(FilePath) == true)
//{
// //清除TXT文本的内容
// FileStream stream2 = File.Open(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
// stream2.Seek(0, SeekOrigin.Begin);
// stream2.SetLength(0); //清空txt文件
// stream2.Close();
//}

MSG = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " : " + MSG + "\r\n";

//重新记录txt内容
FileStream fs = new FileStream(FilePath, FileMode.Append);
//获取字节数组
byte[] data = System.Text.Encoding.Default.GetBytes(MSG);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区,关闭流
fs.Flush();
fs.Close();

posted on 2018-10-05 23:34  asdyzh  阅读(160)  评论(0编辑  收藏  举报

导航