Michael Terrian
Michael Terrian

Reputation: 23

if statements to evaluate multiple file dates

I am new to C# (less than a week), I have the following code that deletes a file on a volume. It is a back up file for an SQL database. And it keeps growing so periodically I have to rename the file and then delete it after a new file is backed up. I need to evaluate if the backup ran and then it is okay to delete the file.

    using System;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // Delete a file found on the D:\ volume.
        // If the file is not found (File doesn't exist),
        // then you will get an exception.
        //
        try
        {
            File.Delete(@"\\Fabtrol-2\Program Files (x86)\FabTrolBackUp\FT_Trans_Log_Appendedold.BAK"); // Try to delete
            Console.WriteLine("Deleted"); // Success
        }
        catch (IOException ex)
        {
            Console.WriteLine(ex); // Write error
        }
    }
}

This is the logic. If I'm asking too much let me know:

Upvotes: 1

Views: 353

Answers (7)

Nick Bray
Nick Bray

Reputation: 1963

This code 1st checks if the file based on the day is less than 2 days old, then if it is it deletes the file FT_Trans_Log_Appendedold.BAK.

                string dir = @"\\Fabtrol-2\Program Files (x86)\FabTrolBackUp\";
                string fileName = dir;
                switch (DateTime.Now.DayOfWeek)
                {
                    case DayOfWeek.Monday:
                        fileName += "FT_FabTrol_Sun_Full.BAK";
                        break;
                    case DayOfWeek.Tuesday:
                        fileName += "FT_FabTrol_Mon_Full.BAK";
                        break;
                    case DayOfWeek.Wednesday:
                        fileName += "FT_FabTrol_Tues_Full.BAK";
                        break;
                    case DayOfWeek.Thursday:
                        fileName += "FT_FabTrol_Wed_Full.BAK";
                        break;
                    case DayOfWeek.Friday:
                        fileName += "FT_FabTrol_Thurs_Full.BAK";
                        break;
                    case DayOfWeek.Saturday:
                        fileName += "FT_FabTrol_Fri_Full.BAK";
                        break;
                    case DayOfWeek.Sunday:
                        fileName += "FT_FabTrol_Sat_Full.BAK";
                        break;
                }

                FileInfo fi = new FileInfo(fileName);
                if (fi.Exists && DateTime.Now.AddDays(-2) > fi.LastWriteTime.Date)
                {
                    (new FileInfo(dir + "FT_Trans_Log_Appendedold.BAK")).Delete();
                    Console.WriteLine("Deleted");
                }

Upvotes: 0

Gray
Gray

Reputation: 7140

Updated my answer to meet your requirements. Kinda weird, but I was bored. May be helpful if just to read.

//2 days
TimeSpan daysToKeep = new TimeSpan(2,0,0,0);

//The folder where the files are kept
DirectoryInfo backupFolder = new DirectoryInfo(@"\\Fabtrol-2\Program Files (x86)\FabTrolBackUp\");
//the Appendold.BAK file
FileInfo backupLog = new FileInfo(backupFolder.FullName + @"\FT_Trans_Log_Appendedold.BAK");

//the base name for the log files
string logName = "FT_FabTrol_{0}_Full.BAK";
//an array for the days of week that are part of the logname
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
//get yesterday's log file name
string yesterdayLog = String.Format(logName, days[(int)DateTime.Today.AddDays(-1).DayOfWeek]);
//create file info
FileInfo logFile = new FileInfo(backupFolder.FullName + yesterdayLog);

//if the file exists, and it is less than 2 days old
try
{
    if (logFile.Exists && (DateTime.Today - logFile.LastWriteTime < daysToKeep))
    {
        backupLog.Delete();
        Console.WriteLine("success");
    }
    else
    {
        Console.WriteLine("log file either did not exist or is not ready to delete");
    }
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

Upvotes: 0

Praveen
Praveen

Reputation: 56509

Try below code.

 string backupFile = @"\\Fabtrol-2\Program Files (x86)\FabTrolBackUp\FT_Trans_Log_Appendedold.BAK";
 FileInfo fi = new FileInfo(backupFile);
 DateTime fileCreatedDate = File.GetCreationTime(backupFile);
 DateTime today = DateTime.Now;
 if (today.DayOfWeek != DayOfWeek.Monday && fileCreatedDate > today.AddDays(-2))
     {
        fi.Delete();
     }

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

All you need to do is iterate over all the files in your folder and delete the ones that are older than two days, right (that seems to be what your giant conditional statement comes down to)?

So, use the following line to get all the files in the folder:

string[] files = Directory.GetFiles(<folder name>);

Then, in a loop, iterate over all the file names in files and check, whether they are old enough.

To get the timestamp of the file, use FileInfo and LastWriteTime like this:

if(DateTime.Today - someFileInfoObject.LastWriteTime.Date > new TimeSpan(2,0,0,0))
{
    File.Delete(); 
}

Upvotes: 1

Todd Richardson
Todd Richardson

Reputation: 1129

Building on what @Gray commented, the FileInfo object will also let you know if it .Exists or not, alleviating the need to depend on the try/catch to know if a file is still there.

Consider the following:

static void Main()
{
    FileInfo fi = new FileInfo(@"\\path\\to\\file.bak");

    if(fi.Exists)
    {
        try
        {
            //because we can still get errors based on permissions etc.
            fi.Delete(); 
            Console.WriteLine("Deleted"); // Success
        }
        catch (IOException ex)
        {
            Console.WriteLine(ex); // Write error
        }  
    }
}

Upvotes: 0

DGibbs
DGibbs

Reputation: 14618

You can simplify that logic greatly with: -

FileInfo info = new FileInfo(@"\\Fabtrol-2\Program Files (x86)\FabTrolBackUp\FT_Trans_Log_Appendedold.BAK");
if(DateTime.Now.AddDays(-2) > info.LastWriteTime.Date)
{
    //Delete
}

Upvotes: 2

Philip Gullick
Philip Gullick

Reputation: 995

Personally for one weeks experience I would say you've jumped into the deep end.

I'm not going to provide code, rather direct you to improve your learning, this is referred to psuedo code

  1. Look into streamwriter/reader and filewriter and fileinfo.
  2. From this you can then read files, delete/rename/whatever you want really.
  3. You then need to try and understand how could I validate what I'm doing. Unfortunately for a beginner this is harder than you may think, possibly harder than the first two points for some people. Think from simple onwards, we developers usually over complicate things. This part is actually rather easy so long your file stuff is correct!

You may want to look into unit testing as this may help your validation.

Upvotes: 0

Related Questions