CSVHelper.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using ivf_tl_Entity.Enums;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace ivf_tl_Service
  9. {
  10. public class CSVHelper
  11. {
  12. //目录
  13. public static string path = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\incubator_logs\\";
  14. //死锁
  15. private static object loglock = new object();
  16. public static void Write(string filename, string content)
  17. {
  18. lock (loglock)
  19. {
  20. try
  21. {
  22. if (!Directory.Exists(path))//如果日志目录不存在就创建
  23. {
  24. Directory.CreateDirectory(path);
  25. }
  26. //创建或打开日志文件,向日志文件末尾追加记录
  27. StreamWriter mySw = File.AppendText(path + filename);
  28. //向日志文件写入内容
  29. string write_content = content;
  30. mySw.WriteLine(write_content);
  31. //关闭日志文件
  32. mySw.Close();
  33. }
  34. catch
  35. {
  36. }
  37. }
  38. }
  39. /// <summary>
  40. /// 写文件,覆盖false,追加true
  41. /// </summary>
  42. /// <param name="filename">文件名</param>
  43. /// <param name="content">内容</param>
  44. /// <param name="isAppend">覆盖false,追加true</param>
  45. public static void WriteFile(string filename, string content, bool isAppend)
  46. {
  47. lock (loglock)
  48. {
  49. try
  50. {
  51. if (isAppend)
  52. {
  53. if (!File.Exists(filename))
  54. {
  55. return;
  56. }
  57. }
  58. else
  59. {
  60. FileStream fs = System.IO.File.Create(filename);
  61. fs.Close();
  62. }
  63. using (System.IO.StreamWriter mySw = new System.IO.StreamWriter(filename, isAppend, System.Text.Encoding.UTF8))
  64. {
  65. mySw.WriteLine(content);
  66. mySw.Flush();
  67. mySw.Close();
  68. }
  69. }
  70. catch (Exception ex)
  71. {
  72. Log4netHelper.WriteLog("写CSV文件", ex);
  73. }
  74. }
  75. }
  76. }
  77. }