简体   繁体   中英

How to repeatedly generate output file with same name

I've a service that generates multiple output files for every iteration run. It runs one time a day. The output filename is always constant and the older file is deleted and then replaced by a new one. For eg:

Output files generated for todays iteration will be

  • abc.txt
  • def.txt
  • ghi.txt

Output files generate for tomorows iteration will delete the older files and the create new files

  • abc.txt
  • def.txt
  • ghi.txt

I'm using the following function in order to achieve what I said.

public static void CreateOutputFile(string Message, string fileName)
{
    try
    {
        string filePath = ConfigurationManager.AppSettings["DESTDIRPATH"] + Path.DirectorySeparatorChar + fileName;
        if (File.Exists(filePath)) //Check if file exists if yes then compare last modified date and delete the older file
        {
            DateTime dateTime = File.GetLastWriteTime(filePath);
            if (dateTime < System.DateTime.Now.AddHours(-5))
            {
                File.Delete(filePath);
            }
        }
        
        if (!File.Exists(filePath)) //Check if file exists if yes then append else create a new file.
        {
            using (StreamWriter sw = File.CreateText(filePath))
            {
                sw.WriteLine(Message);
            }
        }
        else
        {
            using (StreamWriter sw = File.AppendText(filePath))
            {
                sw.WriteLine(Message);
            }
        }
    }
    catch (Exception ex)
    {
        WriteToFile(ex.Message);
    }
}

This works fine but I'm sure there must be better/optimised/improved code for the above snippet. So please let me know your suggestions for the same.

Thank you.

One suggestion is to replace the IF block that contains the calls to File.CreateText and FileAppendText with a single call to StreamWriter. Both methods are wrapper methods that call StreamWriter. The only different is what they pass in for the append flag. In your case the value will be true for append if file exist or otherwise create the file.

Example 1:

        //Check if file exists if yes then compare last modified date and delete the older file
        if (File.Exists(filePath))
        {
            DateTime dateTime = File.GetLastWriteTime(filePath);
            if (dateTime < System.DateTime.Now.AddHours(-5))
            {
                File.Delete(filePath);
            }
        }

        using (StreamWriter sw = new StreamWriter(filePath,true))
            sw.WriteLine(Message);

Example 2: Utilizing additional file access options:

        using (FileStream fs = new FileStream(filePath,             // File full path
                                              FileMode.Append,      // Open for append or create
                                              FileAccess.Write,     // Write mode only
                                              FileShare.ReadWrite)) // Open for Shared Read/Write access
        using (StreamWriter sw = new StreamWriter(fs))
            sw.WriteLine(Message);

See File.cs for File.CreaeText and File.AppendText source code implementation.

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