(1)为防止多任务读取当我们进行读取时需要添加读取锁保证可以依次写入,否则可能出现被占用异常。
(2)创建文本流FileStream及写入流StreamWriter,直接进行数据写入。
(3)读取完成释放资源。并解锁。
3.写入日志
使用:JIYUWU.TXT.TXTHelper.WriteLog(“文本内容”,“单个文件大小(选填默认1M)”,“目录下文件数量(选填默认20个)”,“输出目录(选填默认bin文件下)”)
public static void WriteLog(string content, int fileSize = 1, int fileCount = 20, string filePath = "")
{
try
{
if (!string.IsNullOrWhiteSpace(filePath))
{
logPath = filePath;
}
LogLock.EnterWriteLock();
logPath = logPath.Replace("file:", "");//这里为了兼容webapi的情况
string dataString = DateTime.Now.ToString("yyyy-MM-dd");
string path = logPath + "MyLog";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
path += "";
path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
FileStream fs = new FileStream(path, FileMode.Create);
fs.Close();
}
else
{
int x = System.IO.Directory.GetFiles(path).Count();
path += "";
Dictionary<string, DateTime> fileCreateDate = new Dictionary<string, DateTime>();
string[] filePathArr = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly);
if (filePathArr.Length == 0)
{
string sourceFilePath = path;
path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
FileStream fs = new FileStream(path, FileMode.Create);
fs.Close();
filePathArr = Directory.GetFiles(sourceFilePath, "*.txt", SearchOption.TopDirectoryOnly);
}
for (int i = 0; i < filePathArr.Length; i++)
{
FileInfo fi = new FileInfo(filePathArr[i]);
fileCreateDate[filePathArr[i]] = fi.CreationTime;
}
fileCreateDate = fileCreateDate.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value);
FileInfo fileInfo = new FileInfo(fileCreateDate.Last().Key);
if (fileInfo.Length < 1024 * 1024 * fileSize)
{
path = fileCreateDate.Last().Key;
}
else
{
path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
FileStream fs = new FileStream(path, FileMode.Create);
fs.Close();
}
if (x > fileCount)
{
File.Delete(fileCreateDate.First().Key);
}
}
FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs2);
long fl = fs2.Length;
fs2.Seek(fl, SeekOrigin.Begin);
sw.WriteLine(DateTime.Now.ToString("hh:mm:ss") + "---> " + content);
sw.Flush();
sw.Close();
fs2.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
LogLock.ExitWriteLock();
}
}










