简体   繁体   中英

Writing a CSV log file

I have a Winforms program that needs to log data points into a .CSV file. 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. 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:

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

But, of course, if you check the documentation for 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'

You can also write the csv file using this. 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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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