一段C#保存数据的示例代码

 1 #region 保存数据
 2   public void WriteCSV(string text)
 3   {
 4     object _lock = new object();
 5     string path = Environment.CurrentDirectory + "\\生产数据";
 6     if (!Directory.Exists(path))
 7     {
 8       Directory.CreateDirectory(path);
 9     }
10     string fileFullFileName = path +"\\"+ DateTime.Now.ToString("yyyy_MM_dd") + ".csv";
11     System.IO.StreamWriter sw = null;
12     if (!File.Exists(fileFullFileName))
13     {
14           FileStream fs = new FileStream(fileFullFileName, FileMode.Create);
15       using (sw = new StreamWriter(fs, Encoding.GetEncoding("GB2312")))
16       {
17         string str = "Date,Time,标签编号,条码编号,解码内容";
18         sw.WriteLine(str);
19       }
20     }
21     lock (_lock)
22     {
23       FileStream fs = new FileStream(fileFullFileName, FileMode.Append);
24       try
25       {
26         using (sw = new StreamWriter(fs, Encoding.Default))
27         {
28           sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd,HH:mm:ss,") +text+'\t');//避免写入纯数字后用Excel打开显示成科学计数法的问题
29         }
30       }
31       catch
32       {
33         foreach (Process process in System.Diagnostics.Process.GetProcesses())
34         {
35           if (process.ProcessName.ToUpper().Equals("ET"))
36             process.Kill();    //杀进程
37         }

39 Thread.Sleep(200); 40 using (sw = new StreamWriter(fs, Encoding.Default)) 41 { 42 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd,HH:mm:ss:,") + text+'\t'); 43 } 44 } 45 } 46 } 47 #endregion

 

posted @ 2023-07-18 16:14  尼古拉-卡什  阅读(105)  评论(0编辑  收藏  举报