-2

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
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
EverActive
  • 15
  • 4

2 Answers2

3

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 is for get the CSV file of specific duration

  1. Frist make separate code in that code you Frist get input duration for getting CSV file

Then find the saved CSV files for that duration & get the data from those CSV file & create new CSV file & insert in this new file

So using this solution if you want any duration CSV file you will get & you have also every hour CSV file.

1

You can create the file in the Main method and store the path somewhere globally accessible, e.g.

internal static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        logFilePath = Path.Combine(Application.StartupPath, $"Log_{DateTime.Now:dd-MM-yyyy-HH-mm-ss}.csv");

        File.WriteAllText(logFilePath, "file header here");

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    public static string logFilePath;
}

You can then call File.AppendAllText or File.AppendAllLines to write to the file where and when needed, using Program.logFilePath as the file path. You could even create your own dedicated class that contains the file path and has methods to do the writing, but I'll leave that to you.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46