public static bool CreateWrite(string path, string context)
{
bool b = false;
try
{
LogLock.EnterWriteLock();
FileStream fs = new FileStream(path, FileMode.Create);
//获得字节数组
byte[] data = System.Text.Encoding.Default.GetBytes(context);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
return b;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return b;
}
finally
{
LogLock.ExitWriteLock();
}
}
(2.在文本文件末尾追加写入
使用:JIYUWU.TXT.TXTHelper.WriteAppend(“文件物理路径”,“文本内容”)
public static bool WriteAppend(string path, string context)
{
bool b = false;
try
{
LogLock.EnterWriteLock();
FileStream fs = new FileStream(path, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.Write(context);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
return b;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return b;
}
finally
{
LogLock.ExitWriteLock();
}
}
(3.自动判断换行追加或创建文本
使用:JIYUWU.TXT.TXTHelper.CreateOrWriteAppendLine(“文件物理路径”,“文本内容”)
public static bool CreateOrWriteAppendLine(string path, string context)
{
bool b = false;
try
{
LogLock.EnterWriteLock();
if (!File.Exists(path))
{
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
long fl = fs.Length;
fs.Seek(fl, SeekOrigin.End);
sw.WriteLine(context);
sw.Flush();
sw.Close();
fs.Close();
b = true;
}
else
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
long fl = fs.Length;
fs.Seek(fl, SeekOrigin.Begin);
sw.WriteLine(context);
sw.Flush();
sw.Close();
fs.Close();
b = true;
}
return b;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return b;
}
finally
{
LogLock.ExitWriteLock();
}
}
实现解析:










