/// <summary> /// SFTP procedure to upload or download files /// </summary> /// <param name="blShuttingDown"></param> public void SFTP(ref bool blShuttingDown) { SftpClient sftp = null; try { string upassword = ""; AES256 aes = new AES256(ep); if (_password.Length > 0) { upassword = aes.Decrypt(_password); } if (string.IsNullOrEmpty(KeyFileDirectory)) { sftp = new SftpClient(Host, Port, Username, upassword); } else { KeyFiles = Common.WalkDirectory(KeyFileDirectory, ref blShuttingDown); List<PrivateKeyFile> PKeyFiles = new List<PrivateKeyFile>(); foreach (FileInfo kfile in KeyFiles) { PrivateKeyFile p; if (UsePassPhrase) { p = new PrivateKeyFile(kfile.FullName, upassword); } else { p = new PrivateKeyFile(kfile.FullName); } PKeyFiles.Add(p); } sftp = new SftpClient(Host, Port, Username, PKeyFiles.ToArray()); } BackupFolder = BackupFolder.Replace("\\\\", "\\"); UploadFiles = Common.WalkDirectory(BackupFolder, ref blShuttingDown, FileNameFilter); sftp.Connect(); upassword = ""; _evt.WriteEntry("Remote Sync SFTP: Connected successfully to Host: " + Host, System.Diagnostics.EventLogEntryType.Information,1005, 10); switch (TransferDirection) { case TransferDirectionOptions.Upload: List<DirectoryInfo> Dirs = null; Stream ureader = null; try { string strRemotePath = ""; strRemotePath = Common.FixNullstring(RemoteDirectory); if (RemoteDirectory != "") { strRemotePath = RemoteDirectory + "/"; } strRemotePath = Common.RemotePathClean(Common.FixNullstring(strRemotePath)); BackupFolder = Common.WindowsPathClean(Common.FixNullstring(BackupFolder)); if (!string.IsNullOrEmpty(strRemotePath)) { if (!sftp.Exists(strRemotePath)) { sftp.CreateDirectory(strRemotePath); } sftp.ChangeDirectory(strRemotePath); } //Create Directories Dirs = Common.GetAllDirectories(BackupFolder); foreach (DirectoryInfo dir in Dirs) { if (blShuttingDown) { throw new Exception("Shutting Down"); } try { strRemotePath = dir.FullName; strRemotePath = Common.RemotePathCombine(RemoteDirectory, strRemotePath, BackupFolder); if (blShuttingDown) { _evt.WriteEntry("Remote Sync: Shutting Down, about to Create a Folder: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1040, 10); return; } } catch (Exception) { _evt.WriteEntry("Remote Sync: Folder Path Text Formatting Error: " + strRemotePath, System.Diagnostics.EventLogEntryType.Error, 1040, 10); } try { sftp.CreateDirectory(strRemotePath); _evt.WriteEntry("Remote Sync: Folder Created on " + Host + ": " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1040, 10); } catch (Exception) { } } //Upload every file found and place in the correct directory UploadFiles = Common.WalkDirectory(BackupFolder, ref blShuttingDown, FileNameFilter); foreach (FileInfo ufile in UploadFiles) { try { bool blFileFound = false; bool blOverwriteFile = false; if (blShuttingDown) { throw new Exception("Shutting Down"); } strRemotePath = ufile.DirectoryName; strRemotePath = Common.RemotePathCombine(Common.FixNullstring(RemoteDirectory),strRemotePath,Common.FixNullstring(BackupFolder)); if (!string.IsNullOrEmpty(strRemotePath)) { sftp.ChangeDirectory(strRemotePath); } strRemotePath = Common.RemotePathCombine(strRemotePath, ufile.Name); if (sftp.Exists(strRemotePath)) { blFileFound = true; //if (!((ufile.LastWriteTimeUtc == sftp.GetLastWriteTimeUtc(strRemotePath)))) SftpFile mupload = sftp.Get(strRemotePath); if (ufile.Length != mupload.Length) { blOverwriteFile = true; } } if (sftp.Exists(strRemotePath + ".7z")) { blFileFound = true; SftpFile mupload = sftp.Get(strRemotePath + ".7z"); //File Size can't be used to compare and last write time cannot be modified so can't compare blOverwriteFile = true; //Overwrite Options can be specified by the user /*if (!((ufile.LastWriteTimeUtc == mupload.LastWriteTimeUtc))) { blOverwriteFile = true; }*/ } if (blShuttingDown) { _evt.WriteEntry("Remote Sync: Shutting Down, about to possibly upload a file: " + ufile.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1010, 10); return; } if ((blFileFound == false || blOverwriteFile || (Overwrite == OverwriteOptions.ForceOverwrite && blFileFound)) && !(Overwrite == OverwriteOptions.NoOverwrite && blFileFound == true)) { /*if (sftp.Exists(ufile.FullName)) { SftpFileAttributes fa=sftp.GetAttributes(ufile.FullName); fa.OwnerCanWrite = true; fa.OthersCanWrite = true; fa.GroupCanWrite = true; sftp.SetAttributes(ufile.FullName,fa); sftp.DeleteFile(ufile.FullName); }*/ ureader = new FileStream(ufile.FullName, FileMode.Open); //sftp.UploadFile(File.OpenRead(ufile.FullName), strRemotePath); sftp.UploadFile(ureader, strRemotePath); _evt.WriteEntry("Remote Sync SFTP: File Uploaded: " + ufile.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1010, 10); ureader.Close(); ureader = null; //sftp.SetLastWriteTime(ufile.Name, ufile.LastWriteTimeUtc); //not implemented yet } } catch (Exception ex) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + "Upload of FileName: " + ufile.FullName + " Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } } } catch (Exception exsftup) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + " Error: " + exsftup.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } finally { if (Dirs != null) { Dirs.Clear(); } Dirs = null; if (ureader != null) { ureader.Close(); ureader = null; } if (UploadFiles != null) { UploadFiles.Clear(); } UploadFiles = null; } break; case TransferDirectionOptions.Download: List<RemoteFile> RemoteFiles=null; try { if (!string.IsNullOrEmpty(RemoteDirectory)) { sftp.ChangeDirectory(RemoteDirectory); } RemoteFiles = Common.GetRemoteDirectories(RemoteDirectory, sftp, ""); //Creates Folder Locally in the BackupFolder Common.CreateLocalFolderStructure(RemoteFiles, BackupFolder); //Downloads Files in each directory foreach (RemoteFile ftpfile in RemoteFiles) { string DownloadPath = ""; string strLocalFilePath = ""; string strRemoteFilePath = ""; if (blShuttingDown) { throw new Exception("Shutting Down"); } try { DownloadPath = Common.RemotePathCombine(RemoteDirectory,ftpfile.ParentDirectory); if (!ftpfile.IsDirectory) { strLocalFilePath = Common.WindowsPathCombine(BackupFolder, ftpfile.ParentDirectory); strLocalFilePath = Common.WindowsPathCombine(strLocalFilePath, ftpfile.Name); strRemoteFilePath = Common.RemotePathCombine(DownloadPath, ftpfile.Name); if (blShuttingDown) { if (sftp != null) { if (sftp.IsConnected) { sftp.Disconnect(); } sftp.Dispose(); } _evt.WriteEntry("Remote Sync: Shutting Down, about to possibly download a Host: " + Host + " file: " + DownloadPath + "/" + ftpfile.Name + " From: " + strLocalFilePath, System.Diagnostics.EventLogEntryType.Information, 1020, 10); return; } if (Common.DownloadFile(strLocalFilePath, strRemoteFilePath, ftpfile, Overwrite)) { if (Common.FixNullstring(FileNameFilter) != "" && Common.VerifyPattern(FileNameFilter)) { if (Common.FileNameMatchesPattern(FileNameFilter, ftpfile.Name)) { if (File.Exists(strLocalFilePath)) { File.SetAttributes(strLocalFilePath, FileAttributes.Normal); File.Delete(strLocalFilePath); } using (FileStream fs = new FileStream(strLocalFilePath, FileMode.Create)) { sftp.DownloadFile(strRemoteFilePath, fs); _evt.WriteEntry("Remote Sync SFTP: File Downloaded: " + strRemoteFilePath + " Host: " + Host + " To: " + strLocalFilePath, System.Diagnostics.EventLogEntryType.Information, 1020, 10); fs.Close(); } } } else { if (File.Exists(strLocalFilePath)) { File.SetAttributes(strLocalFilePath, FileAttributes.Normal); File.Delete(strLocalFilePath); } using (FileStream fs = new FileStream(strLocalFilePath, FileMode.Create)) { sftp.DownloadFile(strRemoteFilePath, fs); _evt.WriteEntry("Remote Sync SFTP: File Downloaded: " + strRemoteFilePath + " Host: " + Host + " To: " + strLocalFilePath, System.Diagnostics.EventLogEntryType.Information, 1020, 10); fs.Close(); } } } } } catch (Exception exintry) { _evt.WriteEntry("Remote Sync SFTP: File Download Error: " + DownloadPath + "/" + ftpfile.Name + " Host: " + Host + " To: " + strLocalFilePath + " Error: " + exintry.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } } /* //Example Simple Usage RemoteFiles = sftp.ListDirectory("."); foreach (Renci.SshNet.Sftp.SftpFile ftpfile in RemoteFiles) { using (FileStream fs = new FileStream(BackupFolder + "\\" + ftpfile.Name, FileMode.Create)) { sftp.DownloadFile(ftpfile.FullName, fs); } } */ } catch (Exception excon) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + " Error: " + excon.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } finally { if (RemoteFiles != null) { RemoteFiles.Clear(); } RemoteFiles = null; } break; } } catch (Exception ex) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + " Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } finally { if (sftp != null) { if (sftp.IsConnected) { sftp.Disconnect(); } sftp.Dispose(); } sftp = null; } }
/// <summary> /// FTPS procedure to upload or download files /// </summary> /// <param name="blShuttingDown"></param> public void FTPs(ref bool blShuttingDown) { FTPSClient FTPS = null; bool blFileFound = false; bool blOverwriteFile = false; try { FTPS = new FTPSClient(); AES256 aes = new AES256(ep); string upassword = aes.Decrypt(_password); if (Protocol == ProtocolOptions.FTP) { FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.ClearText, null, null, 0, 0, 0, Timeout); } else { if (AllowAnyCertificate) { if (Protocol == ProtocolOptions.FTPsExplicit) { FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested, new RemoteCertificateValidationCallback(ValidateTestServerCertificate), null, 0, 0, 0, Timeout); } else { FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.Implicit, new RemoteCertificateValidationCallback(ValidateTestServerCertificate), null, 0, 0, 0, Timeout); } } else { if (Protocol == ProtocolOptions.FTPsExplicit) { FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, 0, 0, 0, Timeout); } else { FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.Implicit, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, 0, 0, 0, Timeout); } } } _evt.WriteEntry("Remote Sync: FTPS Connected Successfully to: " + Host, System.Diagnostics.EventLogEntryType.Information, 2005, 20); upassword = ""; switch (TransferDirection) { case TransferDirectionOptions.Upload: BackupFolder = BackupFolder.Replace("\\\\", "\\"); IList<DirectoryListItem> RemoteFilesU=null; try { FTPS.SetCurrentDirectory(RemoteDirectory); RemoteFilesU = FTPS.GetDirectoryList(); UploadFiles = Common.WalkDirectory(BackupFolder, ref blShuttingDown, FileNameFilter); //CreateRemote Directories foreach (DirectoryInfo dir in Common.GetAllDirectories(BackupFolder)) { string strRemotePath = ""; strRemotePath=Common.RemotePathCombine(RemoteDirectory, dir.FullName, BackupFolder); if (blShuttingDown) { throw new Exception("Shutting Down"); } if (blShuttingDown) { _evt.WriteEntry("Remote Sync: Shutting down about to possibly create a folder on Host: " + Host + " Folder: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2040, 20); return; } try { FTPS.MakeDir(strRemotePath); _evt.WriteEntry("Remote Sync: Folder Created on " + Host + " : " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2040, 20); } catch (Exception) { } //FTPS.SetCurrentDirectory(strRemotePath); } //Upload Each File foreach (FileInfo fileU in UploadFiles) { if (blShuttingDown) { throw new Exception("Shutting Down"); } try { string strRemotePath = ""; strRemotePath = Common.RemotePathCombine(RemoteDirectory, fileU.DirectoryName, BackupFolder); strRemotePath = Common.RemotePathCombine(strRemotePath, fileU.Name); blFileFound = false; blOverwriteFile = false; try { if (FTPS.GetFileTransferSize(strRemotePath) > 0) { blFileFound = true; if (!(/*(fileU.LastAccessTimeUtc == FTPS.GetFileModificationTime(strRemotePath)) &&*/ ((ulong)fileU.Length == FTPS.GetFileTransferSize(strRemotePath)))) { blOverwriteFile = true; } } } catch (Exception) { //File Not found No Action Necessary on Error } try { if (FTPS.GetFileTransferSize(strRemotePath + ".7z") > 0) { blFileFound = true; //7z file exists but there is no current way to compare the 7zipped file vs the non compressed file so the user overwrite option will force the appropriate action blOverwriteFile = true; /* if (!((fileU.LastAccessTimeUtc == FTPS.GetFileModificationTime(strRemotePath + ".7z")) && ((ulong)fileU.Length == FTPS.GetFileTransferSize(strRemotePath + ".7z")))) { blOverwriteFile = true; } */ } } catch (Exception) { //File Not Found No Action Necessary on Error } if (blShuttingDown) { _evt.WriteEntry("Remote Sync FTPS: Shutting Down about to possible upload a file: " + fileU.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2010, 20); return; } if ((!blFileFound || blOverwriteFile || (Overwrite == OverwriteOptions.ForceOverwrite && blFileFound)) && !(Overwrite == OverwriteOptions.NoOverwrite && blFileFound)) { //This Uploads the file FTPS.PutFile(fileU.FullName, strRemotePath); _evt.WriteEntry("Remote Sync FTPS: File Uploaded: " + fileU.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2010, 20); } } catch (Exception exp) { _evt.WriteEntry("Remote Sync FTPS: Host:" + Host + " Upload FileName: " + fileU.FullName + " Error: " + exp.Message, System.Diagnostics.EventLogEntryType.Error, 2010, 20); } } } catch (Exception exu) { _evt.WriteEntry("Remote Sync FTPS: Upload Error on Host:" + Host + " Error: " + exu.Message, System.Diagnostics.EventLogEntryType.Error, 2010, 20); } finally { if (RemoteFilesU != null) { RemoteFilesU.Clear(); } if (UploadFiles != null) { UploadFiles.Clear(); } RemoteFilesU = null; UploadFiles = null; } break; case TransferDirectionOptions.Download: List<RemoteFile> RemoteFilesD=null; try { FTPS.SetCurrentDirectory(RemoteDirectory); RemoteFilesD = Common.GetRemoteDirectories(RemoteDirectory, FTPS, ""); Common.CreateLocalFolderStructure(RemoteFilesD, BackupFolder); foreach (RemoteFile FileD in RemoteFilesD) { string strLocalFile = ""; string strRemoteFile = ""; if (blShuttingDown) { throw new Exception("Shutting Down"); } try { if (!FileD.IsDirectory) { strLocalFile = Common.WindowsPathCombine(BackupFolder, FileD.ParentDirectory); strLocalFile = Common.WindowsPathCombine(strLocalFile, FileD.Name); strRemoteFile = FileD.FullName; if (Common.DownloadFile(strLocalFile, strRemoteFile, FileD, Overwrite)) { if ((!blFileFound || blOverwriteFile || (Overwrite == OverwriteOptions.ForceOverwrite && blFileFound)) && !(Overwrite == OverwriteOptions.NoOverwrite && blFileFound)) { if (Common.FixNullstring(FileNameFilter) != "" && Common.VerifyPattern(FileNameFilter)) { if (Common.FileNameMatchesPattern(FileNameFilter, FileD.Name)) { FTPS.GetFile(strRemoteFile, strLocalFile); _evt.WriteEntry("Remote Sync FTPS: File Downloaded: " + strRemoteFile + " Host: " + Host + " To: " + strLocalFile, System.Diagnostics.EventLogEntryType.Information, 2020, 20); } } else { FTPS.GetFile(strRemoteFile, strLocalFile); _evt.WriteEntry("Remote Sync FTPS: File Downloaded: " + strRemoteFile + " Host: " + Host + " To: " + strLocalFile, System.Diagnostics.EventLogEntryType.Information, 2020, 20); } } } } } catch (Exception exdi) { _evt.WriteEntry("Remote Sync FTPS: File Download Error: " + strRemoteFile + " Host: " + Host + " To: " + strLocalFile + " Error: " + exdi.Message, System.Diagnostics.EventLogEntryType.Error, 2020, 20); } } } catch (Exception exd) { _evt.WriteEntry("Remote Sync FTPS: Download Error: Host: " + Host + " Error: " + exd.Message, System.Diagnostics.EventLogEntryType.Error, 2020, 20); } finally { if (RemoteFilesD !=null) { RemoteFilesD.Clear(); } RemoteFilesD = null; } break; } } catch (Exception ex) { _evt.WriteEntry("Remote Sync FTPS: Error: Host: " + Host + " Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error, 2000, 20); } finally { if (FTPS != null) { try { FTPS.Close(); } catch (Exception) { } FTPS.Dispose(); } FTPS = null; } }
/// <summary> /// Compress files individually with .7z added on the end of the filename /// </summary> /// <param name="blShuttingDown"></param> private void compressFile(ref bool blShuttingDown) { SevenZip.SevenZipCompressor compressor = null; SevenZip.SevenZipExtractor extractor = null; Stream exreader = null; Stream creader = null; Stream extestreader = null; string[] strfilearr = new string[1]; try { AllFiles = Common.WalkDirectory(SourceFolder, ref blShuttingDown, FileNameFilter); SevenZip.SevenZipBase.SetLibraryPath(Get7ZipFolder()); if (SourceFolder != DestinationFolder) { Common.CreateDestinationFolders(SourceFolder, DestinationFolder); } if (blShuttingDown) { throw new Exception("Shutting Down"); } //Loop through every file foreach (System.IO.FileInfo file1 in AllFiles) { string str7File = Common.WindowsPathClean(file1.FullName + ".7z"); string strDestination = Common.WindowsPathCombine(DestinationFolder, str7File, SourceFolder); bool blArchiveOk = false; if (blShuttingDown) { _evt.WriteEntry("Compress: Shutting Down, about to Compress: " + file1.FullName, System.Diagnostics.EventLogEntryType.Information, 5130, 50); throw new Exception("Shutting Down"); } //Skip over already compressed files if (file1.Extension.ToLower() == ".7z" || file1.Extension.ToLower() == ".zip" || file1.Extension.ToLower() == ".rar") { continue; } if (Common.IsFileLocked(file1)) { _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5130, 50); continue; } if (!startCompressing(file1.LastWriteTime)) { continue; } try { if (File.Exists(strDestination)) { extestreader = new FileStream(strDestination, FileMode.Open); extractor = new SevenZipExtractor(extestreader); //If archive is not corrupted and KeepUncompressed is false then it is ok to delete the original if (extractor.Check() && KeepOriginalFile == false) { FileInfo file2 = new FileInfo(strDestination); //Same File compressed then ok to delete if (file1.LastWriteTime == file2.LastWriteTime && file1.Length == extractor.UnpackedSize && extractor.FilesCount == 1) { //File.SetAttributes(file1.FullName, FileAttributes.Normal); file1.IsReadOnly = false; File.Delete(file1.FullName); } file2 = null; } continue; } } catch (Exception) { _evt.WriteEntry("Compress: Failed to Delete Original File: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50); continue; } finally { if (extestreader != null) { extestreader.Close(); extestreader.Dispose(); extestreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } } //If file already zipped and the last modified time are the same then delete //Compression of individual files strfilearr[0] = file1.FullName; try { compressor = new SevenZip.SevenZipCompressor(); compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2; compressor.CompressionLevel = CompressionLvl; compressor.ArchiveFormat = OutArchiveFormat.SevenZip; if (!string.IsNullOrEmpty(_encryptionPassword)) { compressor.ZipEncryptionMethod = ZipEncryptionMethod.Aes256; } long lFreeSpace = 0; lFreeSpace = Common.DriveFreeSpaceBytes(DestinationFolder); //Check for Enough Free Space to compress the file if (((file1.Length * 2) > lFreeSpace) && (lFreeSpace != -1)) { _evt.WriteEntry("Compress: Not enough available free space to compress this file: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50); compressor = null; continue; } if (lFreeSpace == -1) { _evt.WriteEntry("Compress: Only files local to this machine should be compressed. Performance problem can occur with large files over the network. " + file1.FullName, System.Diagnostics.EventLogEntryType.Warning, 5150, 50); } //Compress or Compress and Encrypt Files if (!string.IsNullOrEmpty(_encryptionPassword)) { creader = new FileStream(str7File, FileMode.OpenOrCreate); //Encrypt the file if password is specified AES256 aes = new AES256(ep); string upassword = aes.Decrypt(_encryptionPassword); compressor.CompressFilesEncrypted(creader, upassword, strfilearr); creader.Close(); creader.Dispose(); creader = null; exreader = new FileStream(str7File, FileMode.Open); extractor = new SevenZipExtractor(exreader, upassword); upassword = ""; } else { if (Common.IsFileLocked(file1)) { _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5070, 50); continue; } creader = new FileStream(str7File, FileMode.OpenOrCreate); compressor.CompressFiles(creader, strfilearr); creader.Close(); creader.Dispose(); creader = null; exreader = new FileStream(str7File, FileMode.Open); extractor = new SevenZipExtractor(exreader); } //7Zip file ok? blArchiveOk = extractor.Check(); exreader.Close(); exreader.Dispose(); exreader = null; verifyArchive(blArchiveOk, str7File, file1.FullName); } catch (Exception ex) { _evt.WriteEntry("Compress: " + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error, 5000, 50); } finally { if (creader != null) { creader.Close(); creader.Dispose(); creader = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } compressor = null; } }// end foreach _evt.WriteEntry("Compress: Complete Files Compressed: " + FilesCompressed.Count, System.Diagnostics.EventLogEntryType.Information, 5000, 50); } catch (Exception ex) { _evt.WriteEntry("Compress: Compress Files Attempt Failed" + ex.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50); } finally { if (creader != null) { creader.Close(); creader.Dispose(); creader = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } if (extestreader != null) { extestreader.Close(); extestreader.Dispose(); extestreader = null; } compressor = null; } }
/// <summary> /// Compress All Folders in a path each folder to a individual 7zip file /// </summary> /// <param name="blShuttingDown"></param> private void compressFolder(ref bool blShuttingDown) { SevenZip.SevenZipCompressor compressor = null; SevenZip.SevenZipExtractor extractor = null; Stream exreader = null; Stream creader = null; Stream extestreader = null; string[] strfilearr = new string[1]; try { SevenZip.SevenZipBase.SetLibraryPath(Get7ZipFolder()); string[] Directories = Directory.GetDirectories(SourceFolder); //Loop through every local directory foreach (string strDir in Directories) { bool blArchiveOk = false; DirectoryInfo DirInfo1 = new DirectoryInfo(strDir); string str7Dir = Common.WindowsPathClean(DirInfo1.FullName + ".7z"); string strDestination = Common.WindowsPathCombine(DestinationFolder, str7Dir, SourceFolder); if (blShuttingDown) { _evt.WriteEntry("Compress: Shutting Down, about to Compress: " + strDir, System.Diagnostics.EventLogEntryType.Information, 5130, 50); return; } if (!startCompressing(DirInfo1.LastWriteTime)) { continue; } //Check for Original Folder try { if (File.Exists(strDestination)) { FileInfo file7 = new FileInfo(strDestination); extestreader = new FileStream(strDestination, FileMode.Open); extractor = new SevenZipExtractor(extestreader); //If archive is not corrupted and KeepUncompressed is false then it is ok to delete the original if (extractor.Check() && KeepOriginalFile == false) { //Same File compressed then ok to delete if (DirInfo1.LastWriteTime == file7.LastWriteTime && Common.CalculateFolderSize(DirInfo1.FullName) == extractor.UnpackedSize && Common.GetFolderFileCount(DirInfo1.FullName) == extractor.FilesCount) { Directory.Delete(DirInfo1.FullName, true); } } continue; } } catch (Exception) { _evt.WriteEntry("Compress: Failed to Delete Original File: " + DirInfo1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50); continue; } finally { if (extestreader != null) { extestreader.Close(); extestreader.Dispose(); extestreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } } //Compression of Entire Folder strfilearr[0] = DirInfo1.FullName; try { compressor = new SevenZip.SevenZipCompressor(); compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2; compressor.CompressionLevel = CompressionLvl; compressor.ArchiveFormat = OutArchiveFormat.SevenZip; if (!string.IsNullOrEmpty(_encryptionPassword)) { compressor.ZipEncryptionMethod = ZipEncryptionMethod.Aes256; } long lFreeSpace = 0; lFreeSpace = Common.DriveFreeSpaceBytes(DestinationFolder); //Check for Enough Free Space to compress the file if (((Common.CalculateFolderSize(SourceFolder) * 2.0f) > (float)lFreeSpace) && (lFreeSpace != -1)) { _evt.WriteEntry("Compress: Not enough available free space to compress this file: " + DirInfo1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50); compressor = null; continue; } if (lFreeSpace == -1) { _evt.WriteEntry("Compress: Only files local to this machine should be compressed. Performance problem can occur with large files over the network. " + DirInfo1.FullName, System.Diagnostics.EventLogEntryType.Warning, 5150, 50); } //Compress or Compress and Encrypt Files if (!string.IsNullOrEmpty(_encryptionPassword)) { //Compress and Encrypt the Folder if password is specified creader = new FileStream(str7Dir, FileMode.OpenOrCreate); AES256 aes = new AES256(ep); string upassword = aes.Decrypt(_encryptionPassword); compressor.CompressDirectory(DirInfo1.FullName, creader, upassword); creader.Close(); creader.Dispose(); creader = null; exreader = new FileStream(str7Dir, FileMode.Open); extractor = new SevenZipExtractor(exreader, upassword); upassword = ""; } else { //Compress the Folder Normally creader = new FileStream(str7Dir, FileMode.OpenOrCreate); compressor.CompressDirectory(DirInfo1.FullName, creader); creader.Close(); creader.Dispose(); creader = null; exreader = new FileStream(str7Dir, FileMode.Open); extractor = new SevenZipExtractor(exreader); } //7Zip file ok? blArchiveOk = extractor.Check(); //close the archive so it can be deleted later exreader.Close(); exreader.Dispose(); exreader = null; verifyArchive(blArchiveOk, str7Dir, DirInfo1.FullName); } catch (Exception ex) { _evt.WriteEntry("Compress: " + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error, 5000, 50); } finally { if (creader != null) { creader.Close(); creader.Dispose(); creader = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } compressor = null; } }// end foreach _evt.WriteEntry("Compress: Compress Folders Completed", System.Diagnostics.EventLogEntryType.Information, 5000, 50); } catch (Exception ex) { _evt.WriteEntry("Compress: Compress Folders Attempt Failed" + ex.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50); } finally { if (creader != null) { creader.Close(); creader.Dispose(); creader = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } if (extestreader != null) { extestreader.Close(); extestreader.Dispose(); extestreader = null; } compressor = null; } }
/// <summary> /// Extracts 7zip file contents /// </summary> /// <param name="blShuttingDown"></param> private void extract(ref bool blShuttingDown) { SevenZip.SevenZipExtractor extractor = null; Stream exreader = null; //7Zip Extraction of 7zip contents string strDestination = ""; try { SevenZip.SevenZipBase.SetLibraryPath(Get7ZipFolder()); AllFiles = Common.WalkDirectory(SourceFolder, ref blShuttingDown, FileNameFilter); foreach (System.IO.FileInfo file1 in AllFiles) { bool blArchiveOk = false; try { if (blShuttingDown) { if (extractor != null) { extractor.Dispose(); } _evt.WriteEntry("Compress: Shutting Down, about to Extract: " + file1.FullName, System.Diagnostics.EventLogEntryType.Information, 5130, 50); return; } //Skip over already compressed files if (file1.Extension.ToLower() == ".7z" || file1.Extension.ToLower() == ".zip") { if (!startCompressing(file1.LastWriteTime)) { continue; } //If file not already extracted and currently exists if (File.Exists(file1.FullName) && !File.Exists(file1.FullName.Replace(file1.Extension, ""))) { if (Common.IsFileLocked(file1)) { _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5170, 50); continue; } exreader = new FileStream(file1.FullName, FileMode.Open); if (string.IsNullOrEmpty(_encryptionPassword)) { extractor = new SevenZipExtractor(exreader); } else { AES256 aes = new AES256(ep); string upassword = aes.Decrypt(_encryptionPassword); extractor = new SevenZipExtractor(exreader, upassword); upassword = ""; } blArchiveOk = extractor.Check(); //FileInfo file2 = new FileInfo(file1.FullName.Replace(".7z","")); //If archive is not corrupted and KeepUncompressed is false then it is ok to delete the original if (blArchiveOk) { long lFreeSpace = 0; lFreeSpace = Common.DriveFreeSpaceBytes(DestinationFolder); if (((file1.Length * 4) > lFreeSpace) && (lFreeSpace != -1)) { _evt.WriteEntry("Compress: Not enough available free space to compress this file: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50); continue; } if (lFreeSpace == -1) { _evt.WriteEntry("Compress: Only files local to this machine should be compressed. Performance problem can occur with large files over the network. " + file1.FullName, System.Diagnostics.EventLogEntryType.Warning, 5150, 50); } if (string.IsNullOrEmpty(DestinationFolder)) { DestinationFolder = SourceFolder; } strDestination = DestinationFolder; strDestination = Common.WindowsPathCombine(strDestination, file1.DirectoryName, SourceFolder); if (SourceOption == CompressSourceOptions.Folder) { strDestination = Common.WindowsPathCombine(strDestination, Common.WindowsPathClean(Common.Strip7zExtension(file1.FullName)), SourceFolder); if (!Directory.Exists(strDestination)) { Directory.CreateDirectory(strDestination); } } extractor.ExtractArchive(strDestination); FilesCompressed.Add(file1); _evt.WriteEntry("Compress: Successfully Extracted file: " + file1.FullName + " To: " + strDestination, System.Diagnostics.EventLogEntryType.Information, 5170, 50); //Unlock file so that it can be deleted extractor.Dispose(); extractor = null; exreader.Close(); exreader.Dispose(); exreader = null; if (!KeepOriginalFile) { //File.SetAttributes(file1.FullName, FileAttributes.Normal); file1.IsReadOnly = false; File.Delete(file1.FullName); _evt.WriteEntry("Compress: Deleted Original Compressed File: " + file1.FullName + " Per Setting KeepOriginalFile", System.Diagnostics.EventLogEntryType.Information, 5170, 50); } } else { _evt.WriteEntry("Compress: Extract Attempt 7zip Archive Encrypted or Corrupted: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5170, 50); } } } } catch (Exception exe) { _evt.WriteEntry("Compress: Extract Attempt Failed: " + file1.FullName + "Error: " + exe.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50); } finally { if (extractor != null) { extractor.Dispose(); extractor = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } //extractor = null; } } //extract foreach } catch (Exception ex) { _evt.WriteEntry("Compress: Extract Attempt Failed" + ex.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50); } finally { if (extractor != null) { extractor.Dispose(); extractor = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } } }