Advertisement
hmeco

Backup.cs

Jun 2nd, 2012
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.75 KB | None | 0 0
  1. /*
  2. Content of the Backup.cs file
  3. Author by: Hamzalja Meco @ hmeco.dk
  4. */
  5. using ICSharpCode.SharpZipLib.Zip;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Specialized;
  9. using System.IO;
  10. using System.Security.Principal;
  11. using System.Net;
  12. using System.Collections.Generic;
  13.  
  14. namespace BackAndStack
  15. {
  16.     class Backup
  17.     {
  18.  
  19.         static Hashtable excludeDirs = new Hashtable();
  20.         static Hashtable backupHomeFoldes = new Hashtable();
  21.         static string startFolderPath = String.Empty;
  22.         static string outPutTempBackupFolder = String.Empty;
  23.         static string outputZipPath = String.Empty;
  24.         static string password = String.Empty;
  25.         static string ftpUserName = string.Empty;
  26.         static string ftpPassWord = string.Empty;
  27.         static string ftpDomain = "";
  28.         static NameValueCollection configItems;
  29.         [STAThread]
  30.         static void Main(string[] args)
  31.         {
  32.             Console.Title = "BackAndStack v1.0 - by: Hamzalija Meco - http://www.hmeco.dk";
  33.             Console.WriteLine("**************************************************");
  34.             Console.WriteLine("");
  35.             Console.WriteLine("HMECO.DK - BackAndStack V1.0 ");
  36.             Console.WriteLine("");
  37.             Console.WriteLine("**************************************************");
  38.             string fileName = DateTime.Now.ToString(System.Environment.MachineName.ToString() + "_yyyyddmm_hhmm");
  39.             configItems = System.Configuration.ConfigurationSettings.AppSettings;
  40.            
  41.             string[] dirs = configItems["excludeDirs"].ToString().Split('|');
  42.             foreach (string dir in dirs)
  43.                 excludeDirs.Add(dir, dir);
  44.            
  45.             Backup.outputZipPath = configItems["outputZipPath"].ToString();
  46.             Backup.password = configItems["password"].ToString();
  47.             Backup.ftpPassWord = configItems["ftpPassWord"].ToString();
  48.             Backup.ftpUserName = configItems["ftpUserName"].ToString();
  49.  
  50.             string baseSource = Backup.configItems["startFolderPath"].ToString() + System.Environment.UserName.ToString();
  51.             string baseTarget = Backup.configItems["outPutTempBackupFolder"] + "\\" + DateTime.Now.ToString(System.Environment.MachineName.ToString() + "_yyyyddmm").ToString();
  52.  
  53.             stackFilesToTempBackup(baseTarget, baseSource);
  54.  
  55.  
  56.             ZipIt(baseTarget, Backup.outputZipPath +
  57.                 "\\" + fileName + ".zip", Backup.password);
  58.  
  59.             StackBackupToRemoteFolder(fileName);
  60.  
  61.             cleanAfterBackupIsDoneAndDestroySession(baseTarget, fileName);
  62.  
  63.         }
  64.  
  65.         public static void cleanAfterBackupIsDoneAndDestroySession(string baseTarget,string fileName)
  66.         {
  67.             Console.WriteLine("Cleaning up!");            
  68.  
  69.             File.Delete(Backup.outputZipPath + "/" + fileName + ".zip");
  70.  
  71.             System.IO.Directory.Delete(baseTarget, true);
  72.             System.Diagnostics.Process.GetCurrentProcess().Kill();
  73.            
  74.         }
  75.  
  76.         public static void stackFilesToTempBackup(string baseTarget, string baseSource)
  77.         {
  78.  
  79.  
  80.            
  81.             System.IO.FileInfo path = new System.IO.FileInfo(baseTarget);
  82.             path.Directory.Create();
  83.  
  84.             string[] dirs = configItems["backupHomeFoldes"].ToString().Split('|');
  85.             foreach (string dir in dirs)
  86.                 backupHomeFoldes.Add(dir, dir);
  87.  
  88.             foreach (DictionaryEntry Item in backupHomeFoldes)
  89.             {
  90.                 string target = baseTarget + "\\" + Item.Value;
  91.                 System.IO.FileInfo createDir = new System.IO.FileInfo(target);
  92.                 createDir.Directory.Create();
  93.  
  94.                 var stack = new Stack<Folders>();
  95.                 string source = baseSource + "\\" + Item.Value;
  96.                 stack.Push(new Folders(source, target));
  97.  
  98.                 while (stack.Count > 0)
  99.                 {
  100.                     var folders = stack.Pop();
  101.                     Directory.CreateDirectory(folders.Target);
  102.                     foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
  103.                     {
  104.                         string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
  105.                         if (File.Exists(targetFile)) File.Delete(targetFile);
  106.                         File.Copy(file, targetFile);
  107.                     }
  108.  
  109.                     foreach (var folder in Directory.GetDirectories(folders.Source))
  110.                     {
  111.                         stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
  112.                     }
  113.                 }
  114.                 Console.WriteLine("Done Copying folder: " + source);
  115.             }
  116.  
  117.         }
  118.  
  119.         public static void ZipIt(string Path, string outPathAndZipFile, string password)
  120.         {
  121.             Console.WriteLine("Zipping folders to temp zip file and adding a password to it");
  122.             string OutPath = outPathAndZipFile;
  123.             ArrayList ar = GenerateFileList(Path);
  124.  
  125.             int TrimLength = (Directory.GetParent(Path)).ToString().Length;
  126.             TrimLength += 1;
  127.             FileStream ostream;
  128.             byte[] obuffer;
  129.             ZipOutputStream oZipStream = new ZipOutputStream(System.IO.File.Create(OutPath));
  130.             if (password != String.Empty) oZipStream.Password = password;
  131.             oZipStream.SetLevel(9);
  132.             ZipEntry oZipEntry;
  133.             foreach (string Fil in ar)
  134.             {
  135.                 oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
  136.                 oZipStream.PutNextEntry(oZipEntry);
  137.  
  138.                 if (!Fil.EndsWith(@"/"))
  139.                 {
  140.  
  141.                     ostream = File.OpenRead(Fil);
  142.                     obuffer = new byte[ostream.Length];
  143.                     ostream.Read(obuffer, 0, obuffer.Length);
  144.                     oZipStream.Write(obuffer, 0, obuffer.Length);
  145.                     Console.Write(".");
  146.                     ostream.Close();
  147.                 }
  148.             }
  149.             oZipStream.Finish();
  150.             oZipStream.Close();
  151.         }
  152.  
  153.         private static ArrayList GenerateFileList(string Dir)
  154.         {
  155.  
  156.             ArrayList mid = new ArrayList();
  157.             bool Empty = true;
  158.             foreach (string file in Directory.GetFiles(Dir))
  159.             {
  160.                 mid.Add(file);
  161.                 Empty = false;
  162.             }
  163.  
  164.             if (Empty)
  165.             {
  166.                 if (Directory.GetDirectories(Dir).Length == 0)
  167.                 {
  168.                     mid.Add(Dir + @"/");
  169.                 }
  170.             }
  171.             foreach (string dirs in Directory.GetDirectories(Dir))
  172.             {
  173.  
  174.                 string testDir = dirs.Substring(dirs.LastIndexOf(@"\") + 1).ToUpper();
  175.                 if (Backup.excludeDirs.Contains(testDir))
  176.                     continue;
  177.                 foreach (object obj in GenerateFileList(dirs))
  178.                 {
  179.                     mid.Add(obj);
  180.                 }
  181.             }
  182.             return mid;
  183.         }
  184.  
  185.         public static void StackBackupToRemoteFolder(string fileName)
  186.         {
  187.             Console.WriteLine("\n Reading content of the zip file, making shure it is what i expect.");
  188.             byte[] fileContents = null;
  189.  
  190.             try
  191.             {
  192.  
  193.  
  194.                 fileContents = File.ReadAllBytes(Backup.outputZipPath + "/" + fileName + ".zip");
  195.             }
  196.             catch (Exception error)
  197.             {
  198.  
  199.                 Console.WriteLine("Holy cow, something went terrebly wrong: " + error);
  200.                 return;
  201.             }
  202.             try
  203.             {
  204.                 Console.WriteLine("Sending the zip file to its remote location!");
  205.                 Uri myUri = new Uri("ftp://<ftpURL>/" + fileName + ".zip");
  206.                 FtpWebRequest test = (FtpWebRequest)FtpWebRequest.Create(myUri);
  207.                 FtpWebRequest ftpHost = test;
  208.                 ftpHost.UsePassive = true;
  209.                 ftpHost.Method = WebRequestMethods.Ftp.UploadFile;
  210.  
  211.                 ftpHost.Credentials = new NetworkCredential(Backup.ftpUserName, Backup.ftpPassWord, ftpDomain);
  212.                 Stream requestStream = ftpHost.GetRequestStream();
  213.  
  214.                 requestStream.Write(fileContents, 0, fileContents.Length);
  215.                 requestStream.Close();
  216.  
  217.                 Console.WriteLine("Done.");
  218.  
  219.             }
  220.  
  221.             catch (Exception err)
  222.             {
  223.  
  224.                 Console.WriteLine(err);
  225.             }
  226.  
  227.  
  228.         }
  229.     }
  230.     public class Folders
  231.     {
  232.         public string Source { get; private set; }
  233.         public string Target { get; private set; }
  234.  
  235.         public Folders(string source, string target)
  236.         {
  237.             Source = source;
  238.             Target = target;
  239.         }
  240.     }
  241. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement