C#实现多线程写入同一个文件的方法

2019-12-26 13:15:04于丽
  • {  lock (obj) 
  • {  string path = System.Windows.Forms.Application.StartupPath + "app"; 
  • if (!System.IO.Directory.Exists(path))  System.IO.Directory.CreateDirectory(path); 
  • path = path + "" + DateTime.Now.ToString("yyyyMMdd") + ".txt";  StringBuilder sb = new StringBuilder(); 
  • sb.AppendLine("----------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--------------------------");  sb.AppendLine(user.ToString()); 
  • sb.AppendLine("---------------------------------------------------------------------------------");  sb.AppendLine(); 
  • if (!System.IO.File.Exists(path))  System.IO.File.Create(path).Close(); 
  • System.IO.FileStream fileStream = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);  System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream, Encoding.Default); 
  • sw.Write(sb.ToString());  sw.Close(); 
  • sw.Dispose();  fileStream.Close(); 
  • fileStream.Dispose();  } 
  • }  } 
  • 希望本文所述对大家的C#程序设计有所帮助。