From 22552ce1a9f87043048e252ceb5e2175db41fb2a Mon Sep 17 00:00:00 2001 From: Tim Young Date: Sat, 5 Aug 2017 12:41:42 -0500 Subject: [PATCH] Create basic backup file rotation functions and direcories. --- EduNetworkBuilder/NB.cs | 62 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/EduNetworkBuilder/NB.cs b/EduNetworkBuilder/NB.cs index 20d4893..1398eb4 100644 --- a/EduNetworkBuilder/NB.cs +++ b/EduNetworkBuilder/NB.cs @@ -1010,6 +1010,68 @@ namespace EduNetworkBuilder return OFD; } + + /// + /// Move a file out of the way, making a rotating backup at the same time. + /// + /// A source filename with a directory + /// The directory where to put the file + /// The number of rotation backups to make + public static void MoveFileWithRotation(string SourceFileWithDir, string DestDir, int rotation) + { + if (!File.Exists(SourceFileWithDir)) return; //we do not rotate if the source does not exist + if (!Directory.Exists(DestDir)) + Directory.CreateDirectory(DestDir); + //Rotate the old file first, then move the new one over. + string dest_file = Path.Combine(DestDir, Path.GetFileName(SourceFileWithDir)); + RotateFile(dest_file, rotation); + File.Move(SourceFileWithDir, dest_file); + } + + /// + /// Move a file out of the way, making a rotating backup at the same time. backup to appdata + /// + /// A source filename with a directory + /// The number of rotation backups to make + public static void MoveFileWithRotation(string SourceFileWithDir, int rotation) + { + string StandardDest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "EduNetworkBuilder"); + MoveFileWithRotation(SourceFileWithDir, StandardDest, rotation); + } + + /// + /// Given a file, rotate it with the specified number of versions. + /// + /// + /// + public static void RotateFile(string filename, int count) + { + if (count < 1) return; + string currentfile = GenFilenameWithInt(filename, count); + string rotatefile; + if (File.Exists(currentfile)) File.Delete(currentfile); //The last rotation gets deleted + for(int i=count -1; i >= 1; i--) + { + currentfile = GenFilenameWithInt(filename, i); + rotatefile = GenFilenameWithInt(filename, i + 1); + if (File.Exists(currentfile)) + File.Move(currentfile, rotatefile); + } + //The final case is when there is no version number on the file. + currentfile = filename; + rotatefile = GenFilenameWithInt(filename, 1); + if (File.Exists(currentfile)) + File.Move(currentfile, rotatefile); + } + + private static string GenFilenameWithInt(string filename, int version) + { + string FileOnly = Path.GetFileNameWithoutExtension(filename); + string FileWithInt = FileOnly + "-" + version.ToString("00") + Path.GetExtension(filename); + string Combined = Path.Combine(Path.GetDirectoryName(filename), FileWithInt); + return Combined; + } + public static void NotImplimentedMessage() { MessageBox.Show(Translate("NB_NotImplimented"));