Home > Software design >  How to create a single csv log file as long as the program runs in C#?
How to create a single csv log file as long as the program runs in C#?

Time:10-19

At the moment my program creates a new log file every hour with file name as current date and current hour.

enter image description here

There are two disadvantages

  1. For instance, I run the program for 3 hours and 20 minutes and want to have the csv log data of that duration in a single file, but with the present logic it creates 4 separate csv files.

  2. If the end of the previous session and start of the new session happens to be within the same hour, even though I want to have the separate csv log data of the new session, it just appends to the existing file.

Is there any way that I can get rid of these two issues but at the same time keeping the file name as I am doing now?

outputFilePath = csv_directory   CurrentDate   "\\"   CurrentDate   "_"   CurrentHour   ".csv";

if (File.Exists(outputFilePath) == false) 
{
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputFilePath, true))
    {
        // Write File
        // Column Header
        // Data
    }
}
else if (File.Exists(outputFilePath))
{
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputFilePath, true))
    {
        // Write File
        // Data
    }
}

CodePudding user response:

Try following solution

Do not edit the code which is used for saved CSV file in every hour. Code only for save the every hour CSV file.

Below

  • Related