简体   繁体   English

编写CSV日志文件

[英]Writing a CSV log file

I have a Winforms program that needs to log data points into a .CSV file. 我有一个Winforms程序,需要将数据点记录到.CSV文件中。 It's fairly simple, date/time and a double (the data), and go to the next line. 这很简单,日期/时间和双精度(数据),然后转到下一行。

Here's what I have so far (not working, I get an error saying the file is busy/already open - however, it's empty) 这是我到目前为止的内容(无法正常工作,我收到一条错误消息,指出文件正忙/已打开-但是,它为空)

if (!Directory.Exists(SavePath.Text + "\\LOG"))
    Directory.CreateDirectory(SavePath.Text + "\\LOG");

string LogFileName = SavePath.Text + "\\LOG\\Seeing-Log-" + TimeNow.ToString("yyyy-MM-dd") + ".csv";

if (!File.Exists(LogFileName))
    File.Create(LogFileName);

string LogString = TimeNow.ToString("yyyy-MM-dd-_HH-mm-ss") + "," + FWHM_Value.ToString("F:");
File.AppendAllText(LogFileName, LogString + Environment.NewLine);

It's that last line that generates the error. 正是最后一行产生了错误。

Any idea what I am doing wrong? 知道我在做什么错吗?

thanks Steve 谢谢史蒂夫

File.Create returns an open FileStream to the file that's just been created. File.Create将打开的FileStream返回到刚刚创建的文件。 Either change your code to work with FileStream in both the non-existent and existent file cases, or just close the file after creating it: 更改代码以在不存在和存在的文件情况下都可以使用FileStream ,或者仅在创建文件后将其关闭:

if (!File.Exists(LogFileName))
  File.Create(LogFileName).Close();

But, of course, if you check the documentation for AppendAllText : 但是,当然,如果您查看AppendAllText的文档:

Appends the specified stringto the file, creating the file if it does not already exist. 将指定的字符串附加到文件,如果文件不存在,则创建该文件。

You'll realise that the above two lines are completely redundant anyway and can be removed: 您将意识到上述两行无论如何都是完全多余的,可以删除:

if (!Directory.Exists(SavePath.Text + "\\LOG"))
  Directory.CreateDirectory(SavePath.Text + "\\LOG");
string LogString = TimeNow.ToString("yyyy-MM-dd-_HH-mm-ss") + "," + FWHM_Value.ToString("F:");
File.AppendAllText(LogFileName, LogString + Environment.NewLine);

You can even use the free looging tools. 您甚至可以使用免费的清除工具。 Here is one 'log4net' 这是一个“ log4net”

You can also write the csv file using this. 您也可以使用此文件编写csv文件。 I am assuming currently you are not using logging tool. 我假设当前您没有使用日志记录工具。 it will work for you without any code for implementation . 它将为您工作,而无需任何实现代码。

http://element533.blogspot.in/2010/05/writing-to-csv-using-log4net.html http://element533.blogspot.in/2010/05/writing-to-csv-using-log4net.html

Have a great day!! 祝你有美好的一天!!

Replace 更换

File.Create(LogFileName);

with

File.Create(LogFileName).Close();

see this to create empty file. 看到这个创建空文件。

The file is locked when you create it. 创建文件时将其锁定。 Just update your code to this: 只需将代码更新为此:

                File.Create(LogFileName).Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM