简体   繁体   中英

How to check if file has been generate for current month

I am running a windows service which runs every 6 hours and generates files. For some files I want to generate them only once a month.

var todaysDate = DateTime.Now.Date;
var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);
var fileGenerated = false;

if (Convert.ToBoolean(firstOfMonth))
{
    var fileToUploadOne = GenerateFileOne("sproc_name");
    var fileToUploadTwo = GenerateFileTwo("sproc_name");
    fileGenerated = true;
}

How can I make sure the file is generate only once a month.

Updates: Once is month means, generate file one time each month, so that when the services runs every X hours, it does not generate the file over and over again.

The idea is based on saving somewhere on a disk date of last file generation and checking if new month has begun.

You could try this (necessary comments are in code):

class Program
{
    // some safe location
    private static var path = "";

    static void Main(string[] args)
    {
        //get the saved tade
        var saveDate = GetLastSavingDate();
        var today = DateTime.Now;

        //var todaysDate = DateTime.Now.Date;
        //var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
        //var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);
        var fileGenerated = false;

        // check if the difference in months exceeded 1 - this will be true on every 1st of new month, for example 8 - 7 or even 1 - 12
        if(Math.Abs(today.Month - saveDate.Month) >= 1)
        {
            var filetouploadone = generatefileone("sproc_name");
            var filetouploadtwo = generatefiletwo("sproc_name");
            filegenerated = true;
            // save date
            File.WriteAllText(path, JsonConvert.SerializeObject(today));
        }
    }
    //method to get saved date
    private static DateTime GetLastSavingDate()
    {
        var dt = new DateTime();
        return JsonConvert.DeserializeAnonymousType(File.ReadAllText(path), dt);
    }
}

I have taken Console App just for the sake of example, this can be easily applied in WinForms as well.

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