private void ReportBackupSessionResult(BackupResultInfo bckResult, bool isSchedule) { if (_localSettings.ReportingReportToServer) { try { ReportService.BackupSession bckSession = new ReportService.BackupSession() { LocalPath = bckResult.LocalPath, RemotePath = bckResult.RemotePath, BackupMethod = _localSettings.BackupAgentBackupMethod, ChunkCount = bckResult.ChunkCount, CompressedSize = bckResult.CompressedSize, EndTime = bckResult.EndTime, ErrorCode = bckResult.ErrorCode, ErrorMessage = bckResult.ErrorMessage, IsCompressed = bckResult.IsCompressed, IsSchedule = isSchedule, StartTime = bckResult.StartTime }; proxy.RegisterBackupResult(_localSettings.ClientId, bckSession); } catch (Exception ex) { Logger.Write(20030, "An error occurs while trying to register Backup Session Result\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } } }
private void LaunchBackup(PSTRegistryEntry pstFileToSave) { try { Logger.Write(23, "Starting to save " + pstFileToSave.SourcePath, Logger.MessageSeverity.Information); Action SetCurrentFileFinished = () => { chkLstBxPstFiles.SetItemCheckState(_currentFileIndex, CheckState.Indeterminate); }; if (this.InvokeRequired) { this.Invoke(SetCurrentFileFinished); } else { SetCurrentFileFinished(); } _backupThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(_bckEngine.Backup)); _backupThread.IsBackground = true; _backupThread.Start(pstFilesToSave[0]); } catch (Exception ex) { Logger.Write(20021, "An error occurs while starting to backup a PST file.\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } }
/// <summary> /// Gets the list of all Pst files mount in Outlook. /// </summary> /// <returns>A list of file path to each pst file mount in Outlook</returns> public static List <string> GetPstFileList() { List <string> pstFiles = new List <string>(); try { Outlook.Stores stores = new Outlook.Application().Session.Stores; foreach (Outlook.Store store in stores) { try { if (!string.IsNullOrEmpty(store.FilePath) && store.IsDataFileStore && !store.IsCachedExchange) { Logger.Write(30002, "Adding " + store.FilePath.ToLower() + " to the PST list.", Logger.MessageSeverity.Debug); pstFiles.Add(store.FilePath.ToLower()); } } catch (Exception) { } } } catch (Exception ex) { Logger.Write(20001, "Unable to enumerate PST files.\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } return(pstFiles); }
/// <summary> /// Gets the full path to the backup file /// </summary> /// <param name="pstFile">Full path to the PST file</param> /// <returns>Return the full path to the backup file</returns> public string GetBackupFilePath(string pstFile) { string result = String.Empty; using (SQLiteConnection dbConnection = new SQLiteConnection(String.Format("Data Source={0};Version=3;", _dbPath))) { dbConnection.Open(); string sqlCommandText = String.Format("SELECT * FROM tbFiles WHERE SourceFile LIKE '{0}';", pstFile.ToLower()); using (SQLiteCommand sqlCommand = new SQLiteCommand(sqlCommandText, dbConnection)) { SQLiteDataReader reader = sqlCommand.ExecuteReader(); if (reader.HasRows) { if (reader.Read()) { result = reader.GetString(2); } } reader.Close(); dbConnection.Close(); // Déconnexion de la base de données. } } Logger.Write(30009, "The backup filepath for " + pstFile + " is " + result, Logger.MessageSeverity.Debug); return(result); }
/// <summary> /// Add into Registry, new PST files that or not already registred in the registry /// </summary> /// <param name="registryEntries">List of all registry entries.</param> /// <param name="pstFileList">List of all PST files mounted in Outlook.</param> public static void RegisterNewPstFilesInRegistry(List <PSTRegistryEntry> registryEntries, List <string> pstFileList) { try { foreach (string pstFile in pstFileList) { bool found = false; foreach (PSTRegistryEntry regEntry in registryEntries) { if (regEntry.SourcePath.ToLower() == pstFile.ToLower()) { found = true; break; } } if (!found) { PSTRegistryEntry regEntry = new PSTRegistryEntry(pstFile.ToLower()); registryEntries.Add(regEntry); } } } catch (Exception ex) { Logger.Write(20019, "An error occurs while registering new PST files.\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } DeletePstFileRegistryEntries(); for (int i = 0; i < registryEntries.Count; i++) { var regEntry = registryEntries[i]; regEntry.RegistryPath = @"HKEY_CURRENT_USER\Software\PST Backup\PST Files\" + i.ToString(); regEntry.Save(); } }
private void btnSettings_Click(object sender, RibbonControlEventArgs e) { Logger.Write(30003, "User have request to show settings form.", Logger.MessageSeverity.Debug); ThisAddIn.UpdateRegistryEntries(); SmartSingularity.PstBackupSettings.FrmSettings settings = new PstBackupSettings.FrmSettings(); settings.ShowDialog(); }
/// <summary> /// Insert a new row in the tbFiles table. And create "blank" hashes in the tbHashes table. /// </summary> /// <param name="fileId">Unique ID of the file in the database. Enable to make the link with the tbHashes table</param> /// <param name="pstFile">Full path to the PST file</param> /// <param name="backupFile">Full path to the backup file</param> public void RegisterNewPstFile(int fileId, string pstFile, string backupFile) { // Create Pst File in the tbFiles string dbCommand = String.Format("INSERT INTO tbFiles VALUES ({0},'{1}','{2}');", fileId, pstFile.ToLower(), backupFile.ToLower()); ExecuteDbNonQuery(dbCommand); Logger.Write(30007, "Registering a new PST file in the database\r\n" + pstFile + "\r\n" + backupFile, Logger.MessageSeverity.Debug); }
public CoreBackupEngine(ApplicationSettings appSettings) { _appSettings = appSettings; if (!Directory.Exists(FileSystem.ExpandDestinationFolder(appSettings.FilesAndFoldersDestinationPath))) { Logger.Write(30010, "Creating backup folder\r\n" + appSettings.FilesAndFoldersDestinationPath, Logger.MessageSeverity.Debug); FileSystem.CreateDestinationFolder(appSettings.FilesAndFoldersDestinationPath, appSettings.FilesAndFoldersSetExclusiveNTFSPermissions, appSettings.FilesAndFoldersAdditionalNTFSFullcontrol, appSettings.FilesAndFoldersAdditionalNTFSReadWrite); } }
private void Shutdown() { try { Logger.Write(14, "The computer will shutdown now", Logger.MessageSeverity.Information); _timer.Stop(); System.Diagnostics.Process.Start("shutdown", "/p /f"); } catch (Exception) { } }
/// <summary> /// Replace %userlogin% by the login of the current user, and %computename% by the name of the computer /// </summary> /// <param name="fullPath">A string that may contains %userlogin% or %computername%</param> /// <returns>Returns a string where %userlogin% and %computername% have been replace by their respective value</returns> public static string ExpandDestinationFolder(string fullPath) { Logger.Write(30000, "Expanding destination path : " + fullPath, Logger.MessageSeverity.Debug); fullPath = fullPath.ToLower(); fullPath = fullPath.Replace("%userlogin%", Environment.UserName); fullPath = fullPath.Replace("%computername%", Environment.MachineName); Logger.Write(30000, "Expanded path is : " + fullPath, Logger.MessageSeverity.Debug); return(fullPath); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { try { ((Outlook.ApplicationEvents_11_Event)Application).Quit += ThisAddIn_Quit; } catch (Exception ex) { Logger.Write(20017, "An error occurs while linking to Application.Quit in Outlook.exe.\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } }
private int SynchonizeLocalAndRemoteFile(int fileId, string localFile, string remoteFile, List <string> remoteHashes) { int byteCount = 0; int index = 0; byte[] buffer = new byte[_chunkSize]; int chunkSent = 0; string localHash = String.Empty; BackupProgressEventArgs progressEventArgs = new BackupProgressEventArgs(0); Logger.Write(30013, "Synchronizing " + localFile + " with " + remoteFile, Logger.MessageSeverity.Debug); if (!base.IsCancelRequired) { using (FileStream fileToRead = FileSystem.GetOutlookFile(localFile)) { using (Stream fileToWrite = File.OpenWrite(remoteFile)) { do { if (!base.IsCancelRequired) { byteCount = fileToRead.Read(buffer, 0, _chunkSize); localHash = GetHash(buffer); if (index >= remoteHashes.Count || localHash != remoteHashes[index]) { fileToWrite.Position = (long)index * _chunkSize; fileToWrite.Write(buffer, 0, byteCount); chunkSent++; if (index >= remoteHashes.Count) { _clientDb.InsertHash(fileId, index, localHash); } else { _clientDb.UpdateHash(fileId, index, localHash); } } index++; progressEventArgs.Percent = (int)(fileToRead.Position * 100 / fileToRead.Length); BackupProgress(progressEventArgs); } else { break; } } while (fileToRead.Position < fileToRead.Length); } } } Logger.Write(30014, "Synchronizing finish. " + chunkSent + " chunk(s) have been sent to the remote destination", Logger.MessageSeverity.Debug); return(chunkSent); }
public ReportServer() { // ToDo : Handles Log Settings Logger.IsLogActivated = true; Logger.MinimalSeverity = Logger.MessageSeverity.Debug; string databasePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); databasePath = System.IO.Path.Combine(databasePath, "PstBackup", "PstBackup.mdf"); Logger.Write(1, $"Démarrage de ReportServer. Database at {databasePath}", Logger.MessageSeverity.Information); _reportServerDb = new ReportServerDb(databasePath); _reportServerDb.Connect(); }
/// <summary> /// Create a well formated database file if the file does not exists or is malformed /// </summary> public void Initialize() { Logger.Write(30004, "Initializing Database", Logger.MessageSeverity.Debug); if (!ClientDb.IsDbExists(_dbPath)) { CreateDb(); } else if (!IsDbWellFormated()) { System.IO.File.Delete(_dbPath); CreateDb(); } }
/// <summary> /// Compare the free diskspace on the destination disk and the size of a file to know if there is enough diskspace to host the file /// </summary> /// <param name="destinationFolder">A folder on the hard drive to check</param> /// <param name="fileSize">The size of a file that could be host on the hard drive</param> /// <returns>Returns true if there is enough diskspace on the drive to host a file of the provided size</returns> private bool HasEnoughDiskspace(DirectoryInfo destinationFolder, long fileSize) { try { DriveInfo localDrive = new DriveInfo(destinationFolder.Root.ToString()); return(localDrive.AvailableFreeSpace > fileSize); } catch (Exception ex) { Logger.Write(10003, "Unable to determine if there is enough diskspace on " + destinationFolder + "\r\n" + ex.Message, Logger.MessageSeverity.Warning, System.Diagnostics.EventLogEntryType.Warning); } return(true); }
private void SetLogo() { try { System.IO.FileInfo appPath = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location); string logoPath = System.IO.Path.Combine(appPath.DirectoryName, "logo.png"); if (System.IO.File.Exists(logoPath)) { pctBxLogo.Image = new Bitmap(logoPath); pctBxLogo.BorderStyle = BorderStyle.FixedSingle; } } catch (Exception ex) { Logger.Write(20022, "Error while setting Logo.\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } }
/// <summary> /// Delete all rows in the tbFiles table, for which "pstFile" and "backupFile" match the fields "SourceFile" and "DestinationFile" /// </summary> /// <param name="pstFile">Full path of the PST file</param> public void DeletePstFile(string pstFile) { Logger.Write(30008, "Deleting " + pstFile + " from the database", Logger.MessageSeverity.Debug); // Get FileId of the record int fileId = GetFileID(pstFile); // Delete Pst File from the tbPstFiles table string dbCommand = String.Format("DELETE FROM tbFiles WHERE SourceFile LIKE '{0}';", pstFile.ToLower()); ExecuteDbNonQuery(dbCommand); // Delete hashes from the tbHashes table dbCommand = String.Format("DELETE FROM tbHashes WHERE FileId={0};", fileId); ExecuteDbNonQuery(dbCommand); }
/// <summary> /// Returns an instance of class that implement the correct backup method based on the settings /// </summary> /// <param name="appSettings">Settings of the application</param> /// <returns>Returns an instance of IBackupEngine</returns> public static CoreBackupEngine GetBackupEngine(ApplicationSettings appSettings) { switch (appSettings.BackupAgentBackupMethod) { case ApplicationSettings.BackupMethod.Full: return(new FullBackupEngine(appSettings)); case ApplicationSettings.BackupMethod.Differential: return(new DifferentialBackupEngine(appSettings)); default: Logger.Write(10001, "Unable to determine the backup method\r\n" + appSettings.BackupAgentBackupMethod, Logger.MessageSeverity.Warning, System.Diagnostics.EventLogEntryType.Warning); return(new FullBackupEngine(appSettings)); } }
/// <summary> /// Create a folder and set NTFS permissions accordingly to the parameters /// </summary> /// <param name="fullPath">Full path to the folder to create</param> /// <param name="setNtfsRights">True to personnalize NTFS permissions</param> /// <param name="fullControlMembers">Users and Groups that will have NTFS Full Control permission</param> /// <param name="readWriteMembers">Users and Groups that will have NTFS Read and Write permission</param> public static void CreateDestinationFolder(string fullPath, bool setNtfsRights, string fullControlMembers, string readWriteMembers) { DirectoryInfo destinationFolder = new DirectoryInfo(ExpandDestinationFolder(fullPath)); if (setNtfsRights) { Logger.Write(30000, "Creating destination folder with personnalized NTFS permissions", Logger.MessageSeverity.Debug); destinationFolder.Create(GetDirectorySecurity(fullControlMembers, readWriteMembers)); } else { Logger.Write(30000, "Creating destination folder with inherited NTFS permissions", Logger.MessageSeverity.Debug); destinationFolder.Create(); } }
/// <summary> /// Create the file to host the SQLite database and associated tables /// </summary> public void CreateDb() { Logger.Write(30005, "Creating a new database\r\n" + _dbPath, Logger.MessageSeverity.Debug); string sqlCommand; // Create Db file SQLiteConnection.CreateFile(_dbPath); // DDL command to create Files table sqlCommand = "CREATE TABLE tbFiles(fileId INTEGER PRIMARY KEY, sourceFile NVARCHAR(260) UNIQUE, destinationFile NVARCHAR(260) NOT NULL);"; ExecuteDbNonQuery(sqlCommand); // DDL command to create Hashes table sqlCommand = "CREATE TABLE tbHashes(fileId INTEGER NOT NULL, chunkId INTEGER NOT NULL, hash CHARACTER(32) NOT NULL, PRIMARY KEY (fileID,chunkID));"; ExecuteDbNonQuery(sqlCommand); }
private void btnCancel_Click(object sender, EventArgs e) { Logger.Write(11, "User have pressed Cancel button", Logger.MessageSeverity.Information); try { _bckEngine.IsCancelRequired = true; btnCancel.Enabled = false; btnCancel.Refresh(); ReportCanceledBackupSession(); _backupThread.Join(3000); proxy.Close(); } catch (Exception) { } SetExecutionState(ExecutionState.ES_CONTINUOUS); Close(); }
public FrmAgent() { InitializeComponent(); SetLogo(); _localSettings.OverrideLocalSettingsWithGPOSettings(_gpoSettings); txtBxDestination.Text = _localSettings.FilesAndFoldersDestinationPath; try { proxy = new ReportService.ReportServerClient("BasicHttpBinding_IReportServer", GetServerUriFromSettings()); } catch (Exception ex) { Logger.Write(20027, "An error occurs while instanciating the client proxy. Report server will be unreachable\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } RegisterClient(); }
public void Backup() { try { Logger.Write(16, "Starting backup session", Logger.MessageSeverity.Information); if (_localSettings.IsDestinationProperlyDefine()) { _bckEngine = CoreBackupEngine.GetBackupEngine(_localSettings); _bckEngine.OnBackupFinished += BckEngine_OnBackupFinished; _bckEngine.OnBackupProgress += BckEngine_OnBackupProgress; List <PSTRegistryEntry> allPstFiles = ApplicationSettings.GetPstRegistryEntries(); Logger.Write(17, "Found " + allPstFiles.Count + " Pst file(s) registered in Outlook.", Logger.MessageSeverity.Information); #if (DEBUG) System.Random rnd = new Random(DateTime.Now.Millisecond); for (int i = 0; i < allPstFiles.Count; i++) { allPstFiles[i].LastSuccessfulBackup = DateTime.Now.Subtract(new TimeSpan(rnd.Next(72, 300), 0, 0, 0)); } #endif (_bckEngine as CoreBackupEngine).SelectPstFilesToSave(allPstFiles, out pstFilesToSave, out pstFilesToNotSave); RegisterPstFiles(_localSettings.ClientId, pstFilesToSave); RegisterPstFiles(_localSettings.ClientId, pstFilesToNotSave); pstFilesToSave.Sort(); DisplayFileList(pstFilesToSave); if (pstFilesToSave.Count > 0) { SetExecutionState(ExecutionState.ES_CONTINUOUS | ExecutionState.ES_SYSTEM_REQUIRED); SetMaximumOverAllProgressBar(pstFilesToSave.Count); LaunchBackup(pstFilesToSave[0]); this.ShowDialog(); } } else { Logger.Write(10007, "Destination not correctly define. Review application's settings", Logger.MessageSeverity.Warning, System.Diagnostics.EventLogEntryType.Warning); MessageBox.Show(_resMan.GetString("DestinationNotCorrectlyDefine")); } } catch (Exception ex) { Logger.Write(20020, "An error occurs while launching backup.\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); MessageBox.Show(_resMan.GetString("ErrorWhileTryingToBackupFiles")); } }
private void RegisterPstFiles(string clientId, List <PSTRegistryEntry> pstFilesToRegister) { if (_localSettings.ReportingReportToServer) { foreach (PSTRegistryEntry regEntry in pstFilesToRegister) { try { ReportService.PstFile pstFile = GetPstFile(regEntry); proxy.RegisterPstFile(clientId, pstFile); } catch (Exception ex) { Logger.Write(20029, "An error occurs while trying to register a PstFile\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } } } }
private void CopyFile(string sourceFilePath, string outputFilePath, bool isCompressed) { BackupProgressEventArgs progressEventArgs = new BackupProgressEventArgs(0); Logger.Write(30018, "Copying " + sourceFilePath + " to " + outputFilePath, Logger.MessageSeverity.Debug); using (Stream sourceFile = FileSystem.GetOutlookFile(sourceFilePath)) using (Stream outputFile = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write)) { int bufferLength = 1024 * 1024; byte[] buffer = new byte[bufferLength]; long sourceLength = sourceFile.Length; double totalReadBytes = 0; int readBytes = 0; double percentage = 0; while ((readBytes = sourceFile.Read(buffer, 0, bufferLength)) > 0) { totalReadBytes += readBytes; if (isCompressed) { percentage = 50.0 + totalReadBytes * 50.0 / sourceLength; } else { percentage = totalReadBytes * 100.0 / sourceLength; } outputFile.Write(buffer, 0, readBytes); if (base.IsCancelRequired) { outputFile.Close(); (new System.IO.FileInfo(outputFilePath)).Directory.Delete(true); throw new BackupCanceledException(sourceFilePath); } else { progressEventArgs.Percent = (int)percentage; BackupProgress(progressEventArgs); } } } Logger.Write(30019, "Copy completed", Logger.MessageSeverity.Debug); }
private static DirectorySecurity GetDirectorySecurity(string fullControlMembers, string readWriteMembers) { System.Security.AccessControl.DirectorySecurity dirSecturity = new System.Security.AccessControl.DirectorySecurity(); dirSecturity.SetAccessRuleProtection(true, false); // Break inheritance and discard parent's access rules AddReadWriteAccess(dirSecturity, Environment.UserName); // Set Read/Write access for the current user System.Security.Principal.SecurityIdentifier systemSID = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.LocalSystemSid, null); AddAccessRule(dirSecturity, GetFullControlAccessRule(systemSID)); // Set Full Access for "System" Account if (!String.IsNullOrEmpty(readWriteMembers)) { try { foreach (string trustee in readWriteMembers.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { try { AddReadWriteAccess(dirSecturity, trustee); } catch (Exception ex) { Logger.Write(20015, "Unable to set Read/Write permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } } } catch (Exception ex) { Logger.Write(20015, "Unable to set Read/Write permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } } if (!String.IsNullOrEmpty(fullControlMembers)) { try { foreach (string trustee in fullControlMembers.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { try { AddFullControlAccess(dirSecturity, trustee); } catch (Exception ex) { Logger.Write(20016, "Unable to set Full Control permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } } } catch (Exception ex) { Logger.Write(20016, "Unable to set Full Control permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } } return(dirSecturity); }
private void ReportCanceledBackupSession() { if (_localSettings.ReportingReportToServer) { try { BackupResultInfo bckResult = new BackupResultInfo(pstFilesToSave[0]); bckResult.EndTime = DateTime.UtcNow; bckResult.RemotePath = String.Empty; bckResult.ErrorCode = BackupResultInfo.BackupResult.Canceled; bckResult.ErrorMessage = String.Empty; ReportBackupSessionResult(bckResult, true); } catch (Exception ex) { Logger.Write(20031, "An error occurs while trying to register a Canceled Backup Session\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } } }
private void DisplayFileList(List <PSTRegistryEntry> fileList) { DateTime neverBackup = new DateTime(); string pstList = String.Empty; try { foreach (PSTRegistryEntry pstFile in fileList) { DateTime lastBackup = pstFile.LastSuccessfulBackup; chkLstBxPstFiles.Items.Add(pstFile.SourcePath + " : " + (lastBackup == neverBackup ? _resMan.GetString("NeverSaved") : lastBackup.ToShortDateString())); pstList += pstFile.SourcePath + "\r\n"; } Logger.Write(18, "List of PST files to backup : " + pstList, Logger.MessageSeverity.Information); } catch (Exception ex) { Logger.Write(20023, "Error while displaying PST files list.\r\n" + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } }
private void ThisAddIn_Quit() { try { Logger.Write(30001, "Outlook is closing.", Logger.MessageSeverity.Debug); UpdateRegistryEntries(); System.IO.FileInfo currentAssembly = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location); string currentPath = currentAssembly.DirectoryName; #if (DEBUG) string bckAgentPath = @"C:\Users\Courtel\Documents\Visual Studio 2017\Projects\SmartSingularity.PstBackup\SmartSingularity.PstBackupAgent\bin\Debug\SmartSingularity.PstBackupAgent.exe"; #else string bckAgentPath = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Pst Backup", "SmartSingularity.PstBackupAgent.exe"); Logger.Write(30000, "Launching Backup-Agent at " + bckAgentPath, Logger.MessageSeverity.Debug); #endif System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(bckAgentPath)); } catch (Exception ex) { Logger.Write(20000, "Unable to start Backup-Agent." + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); } }
/// <summary> /// Gets a FileStream link to the specified file. If the file is locked, try 5 times at 1 second interval /// </summary> /// <param name="filename">Full path to the file</param> /// <returns>Returns a FileStream link to the file or null if all tries to open the filestream have failed</returns> public static FileStream GetOutlookFile(string filename) { FileStream fs = null; for (int i = 0; i < 5; i++) { try { fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); break; } catch (Exception) { Logger.Write(10006, filename + " lock by another process. Waiting 1 second before retrying.", Logger.MessageSeverity.Warning, System.Diagnostics.EventLogEntryType.Warning); System.Threading.Thread.Sleep(1000); } } return(fs); }