/// <summary>
/// 同步锁
/// </summary>
private static readonly object syncRoot = new object();
/// <summary>
/// 读同步锁
/// </summary>
private static readonly object syncReadRoot = new object();
/// <summary>
/// 覆盖写文件信息
/// </summary>
/// <param name="filePath"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool WriteFileCover(string filePath,string message)
{
bool bRet=false;
try
{
lock (syncRoot)
{
//写入文件
FileStream fs;
StreamWriter sw;
fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
sw = new StreamWriter(fs);
sw.Write(message);//开始写入值
sw.Close();//关闭写入流
fs.Close();//关闭文件流
bRet = true;
}
}
catch (Exception ex)
{
bRet = false;
}
return bRet;
}
/// <summary>
/// 追加写文件信息
/// </summary>
/// <param name="filePath"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool WriteFileAppend(string filePath, string message)
{
bool bRet = false;
try
{
lock (syncRoot)
{
//写入文件
FileStream fs;
StreamWriter sw;
if (!File.Exists(filePath))
{
fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
sw = new StreamWriter(fs);
sw.Write(message);//开始写入值
}
else
{
fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.Write(message);//开始写入值
}
sw.Close();//关闭写入流
fs.Close();//关闭文件流
bRet = true;
}
}
catch (Exception ex)
{
bRet = false;
}
return bRet;
}
/// <summary>
/// 读取文件信息
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string ReadFile(string filePath)
{
string message = "";
lock (syncReadRoot)
{
StreamReader? sr = null;
try
{
if (!File.Exists(filePath))
{
return message;
}
sr = File.OpenText(filePath);
string? nextLine;
while ((nextLine = sr.ReadLine()) != null)
{
message += nextLine;
}
sr?.Close();
}
catch (Exception ex)
{
sr?.Close();
}
}
return message;
}
标签:文件,fs,filePath,C#,读写,sw,new,message,bRet
From: https://www.cnblogs.com/qiutian-hao/p/18356165