Example #1
0
        public static void CopyFile(string from, string to)
        {
            FileInfo MyFileInfo = new FileInfo(from);
            String   _Volume    = MyFileInfo.Directory.Root.Name;

            // VSS step 1: Initialize
            IVssImplementation   _vssImplementation = VssUtils.LoadImplementation();
            IVssBackupComponents _backup            = _vssImplementation.CreateVssBackupComponents();

            _backup.InitializeForBackup(null);

            // VSS step 2: Getting Metadata from all the VSS writers
            _backup.GatherWriterMetadata();

            // VSS step 3: VSS Configuration
            _backup.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
            _backup.SetBackupState(false, true, Alphaleonis.Win32.Vss.VssBackupType.Full, false);

            // VSS step 4: Declaring the Volumes that we need to use in this beckup.
            // The Snapshot is a volume element (Here come the name "Volume Shadow-Copy")
            // For each file that we nee to copy we have to make sure that the propere volume is in the "Snapshot Set"
            Guid MyGuid01 = _backup.StartSnapshotSet();
            Guid MyGuid02 = _backup.AddToSnapshotSet(_Volume, Guid.Empty);

            // VSS step 5: Preparation (Writers & Provaiders need to start preparation)
            _backup.PrepareForBackup();
            // VSS step 6: Create a Snapshot For each volume in the "Snapshot Set"
            _backup.DoSnapshotSet();

            _backup.ExposeSnapshot(MyGuid02, null, VssVolumeSnapshotAttributes.ExposedLocally, "L:");

            // VSS step 8: Copy Files!

            /***********************************
             * /* Now we start to copy the files/folders/disk!
             * /* Execution time can depend on what we are copying
             * /* We can copy one element or several element.
             * /* As long as we are working under the same snapshot,
             * /* the element should be in consist state from the same point-in-time
             * /***********************************/
            String sVSSFile1 = from.Replace(_Volume, @"L:\");

            if (File.Exists(sVSSFile1))
            {
                System.IO.File.Copy(sVSSFile1, to + @"\" + System.IO.Path.GetFileName(from), true);
            }


            // VSS step 9: Delete the snapshot (using the Exposed Snapshot name)
            foreach (VssSnapshotProperties prop in _backup.QuerySnapshots())
            {
                if (prop.ExposedName == @"L:\")
                {
                    Console.WriteLine("prop.ExposedNam Found!");
                    _backup.DeleteSnapshot(prop.SnapshotId, true);
                }
            }

            _backup = null;
        }
Example #2
0
        private static void Zip()
        {
            Log2 vssLog = new Log2(nameof(AddonsBackup) + " - VSS Service");
            // get free drive letter
            string driveLetter = new string[] { "P:", "Q:", "R:", "S:", "T:", "U:", "V:", "W:" }.FirstOrDefault(l => !DriveInfo.GetDrives().Select(m => m.RootDirectory.Name).Contains(l));

            if (driveLetter == default(string))
            {
                throw new IOException("Can't find free drive letter!");
            }
            vssLog.Info($"Free drive letter: {driveLetter}");
            // making VSS snapshot
            IVssImplementation   vssImplementation = VssUtils.LoadImplementation();
            IVssBackupComponents backupComponents  = vssImplementation.CreateVssBackupComponents();

            backupComponents.InitializeForBackup(null);
            vssLog.Info("VssBackupComponents is initialized");
            Guid backupGuid1 = Guid.Empty;

            try
            {
                backupComponents.GatherWriterMetadata();
                backupComponents.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
                backupComponents.SetBackupState(false, true, VssBackupType.Full, false);
                vssLog.Info("VssBackupComponents is set up");
                backupComponents.StartSnapshotSet();
                backupGuid1 = backupComponents.AddToSnapshotSet(new DirectoryInfo(_settings.WoWDirectory).Root.Name, Guid.Empty);
                backupComponents.PrepareForBackup();
                backupComponents.DoSnapshotSet();
                vssLog.Info("Snapshot is taken");
                backupComponents.ExposeSnapshot(backupGuid1, null, VssVolumeSnapshotAttributes.ExposedLocally, driveLetter);
                // zipping
                string zipPath = $"{_settings.WoWAddonsBackupPath}\\AddonsBackup_{DateTime.UtcNow:yyyyMMdd_HHmmss}.zip";
                log.Info("Zipping to file: " + zipPath);
                using (ZipFile zip = new ZipFile(zipPath, Encoding.UTF8))
                {
                    zip.CompressionLevel = (CompressionLevel)_settings.WoWAddonsBackupCompressionLevel;
                    foreach (string dirName in FoldersToArchive)
                    {
                        zip.AddDirectory(_settings.WoWDirectory.Replace(new DirectoryInfo(_settings.WoWDirectory).Root.Name, $"{driveLetter}\\") + "\\" + dirName, "\\" + dirName);
                    }
                    zip.SaveProgress += AddonsBackup_SaveProgress;
                    var processPriority = Process.GetCurrentProcess().PriorityClass;
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
                    zip.Save();
                    Process.GetCurrentProcess().PriorityClass = processPriority;
                    zip.SaveProgress -= AddonsBackup_SaveProgress;
                }
            }
            finally
            {
                VssSnapshotProperties existingSnapshot = backupComponents.QuerySnapshots().FirstOrDefault(l => l.SnapshotId == backupGuid1);
                if (existingSnapshot == default(VssSnapshotProperties))
                {
                    vssLog.Error($"Can't delete snapshot {backupGuid1}");
                }
                else
                {
                    backupComponents.DeleteSnapshot(existingSnapshot.SnapshotId, true);
                    backupComponents.Dispose();
                    vssLog.Info($"Snapshot is deleted ({existingSnapshot.SnapshotId})");
                }
                GC.Collect();
            }
        }
            private void Main()
            {
                string sourceFolder = PathHelper.AppendSeparator(_session.SourceFolder);                                         // C:\,  C:\Folder\, \\Server\Share\, \\Server\Share\Folder\
                string volume       = PathHelper.RemoveTrailingSeparator(Path.GetPathRoot(sourceFolder));                        // C:,   C:,         \\Server\Share,  \\Server\Share
                string pathFromRoot = PathHelper.RemoveTrailingSeparator(sourceFolder.Substring(volume.Length));                 // "",   \Folder,    "",              \Folder

                if (pathFromRoot.Length == 0)
                {
                    pathFromRoot = null;                                                                                             // null, \Folder,    null,            \Folder
                }
                try
                {
                    // helper function throwing an ObjectDisposedException if _disposeEvent is currently signaled
                    Action CheckForDisposeRequest = () => { if (_disposeEvent.WaitOne(0))
                                                            {
                                                                throw new ObjectDisposedException("VscThread");
                                                            }
                    };

                    CheckForDisposeRequest();

                    _backup = VssUtils.LoadImplementation().CreateVssBackupComponents();
                    _backup.InitializeForBackup(null);
                    _backup.SetContext(VssSnapshotContext.Backup);
                    _backup.SetBackupState(false, false, VssBackupType.Copy, false);
                    CheckForDisposeRequest();

                    _backup.GatherWriterMetadata();
                    CheckForDisposeRequest();

                    _snapshotSetID    = _backup.StartSnapshotSet();
                    _volumeSnapshotID = _backup.AddToSnapshotSet(PathHelper.AppendSeparator(volume));
                    CheckForDisposeRequest();

                    _backup.PrepareForBackup();
                    VerifyWriterStatus();
                    CheckForDisposeRequest();

                    // create the snapshot
                    _backup.DoSnapshotSet();
                    VerifyWriterStatus();

                    // mount the source folder as file share
                    // (non-persistent shadow copies cannot be mounted locally on a drive or folder)
                    string shareName = _backup.ExposeSnapshot(_volumeSnapshotID, pathFromRoot,
                                                              VssVolumeSnapshotAttributes.ExposedRemotely, null);
                    _session._mountPoint = @"\\localhost\" + shareName;

                    CheckForDisposeRequest();
                }
                catch (ObjectDisposedException)                 // by CheckForDisposeRequest()
                {
                    Cleanup();
                    return;
                }
                catch (Exception e)
                {
                    Cleanup();

                    string msg = (e is UnauthorizedAccessException
                                                ? "You lack the required privileges to create a volume shadow copy.\nPlease restart RoboMirror as administrator."
                                                : "The volume shadow copy could not be created:\n\n" + e.Message);
                    _session.OnError(msg);

                    return;
                }

                // fire the Ready event
                try { _session.OnReady(); }
                // on unhandled exception by Ready event handler: Cleanup() before rethrowing
                catch { Cleanup(); throw; }

                // wait for Dispose() signal
                _disposeEvent.WaitOne();

                Cleanup();
            }
Example #4
0
        //edit 05.04.2017
        public void StartDiffBackup()
        {
            UpdateSosttask(2);
            IVssBackupComponents backup = null;
            string  namedriver          = "";
            Boolean successtask         = true;

            try
            {
                if (DTask.Shadow == 1)
                {
                    string[]    massdrives = { "A:\\", "B:\\", "D:\\", "E:\\", "I:\\", "K:\\", "L:\\", "M:\\", "N:\\", "O:\\", "P:\\" };
                    string      havedriver = "";
                    DriveInfo[] drives     = DriveInfo.GetDrives();
                    foreach (DriveInfo d in drives)
                    {
                        havedriver = havedriver + d.Name;
                    }
                    foreach (string strdriver in massdrives)
                    {
                        if (!havedriver.Contains(strdriver))
                        {
                            namedriver = strdriver;
                        }
                    }

                    FileInfo MyFileInfo = new FileInfo(DTask.Source);
                    String   _Volume    = MyFileInfo.Directory.Root.Name;

                    IVssImplementation _vssImplementation = VssUtils.LoadImplementation();
                    backup = _vssImplementation.CreateVssBackupComponents();
                    backup.InitializeForBackup(null);

                    backup.GatherWriterMetadata();

                    backup.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
                    backup.SetBackupState(false, true, Alphaleonis.Win32.Vss.VssBackupType.Full, false);

                    Guid MyGuid01 = backup.StartSnapshotSet();
                    Guid MyGuid02 = backup.AddToSnapshotSet(_Volume, Guid.Empty);

                    backup.PrepareForBackup();
                    backup.DoSnapshotSet();

                    backup.ExposeSnapshot(MyGuid02, null, VssVolumeSnapshotAttributes.ExposedLocally, namedriver.Remove(2, 1));

                    DTask.Source = DTask.Source.Replace(_Volume, namedriver);
                }

                StringWriter SW            = new StringWriter();
                StringWriter Skip_file_log = new StringWriter();
                string       time_today    = DateTime.Now.Date.ToShortDateString();
                ZipFile      zf            = new ZipFile(DTask.Dest + "\\" + DTask.Taskname + "_" + time_today.Replace(".", "-") + "." + DTask.Extension);
                zf.ProvisionalAlternateEncoding = Encoding.GetEncoding("cp866");

                if (DTask.Password != "no")
                {
                    zf.Password = DTask.Password;
                }
                zf.UseZip64WhenSaving      = Zip64Option.AsNecessary;
                zf.ZipErrorAction          = ZipErrorAction.Skip;
                zf.StatusMessageTextWriter = Skip_file_log;

                string[] massexeption;
                string[] separator = { Environment.NewLine };
                massexeption = DTask.Exeption.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                Stack <string> dirs = new Stack <string>(20);
                string         root = DTask.Exeption;

                if (!Directory.Exists(root))
                {
                    throw new ArgumentException();
                }
                dirs.Push(root);


                while (dirs.Count > 0)
                {
                    string   currentDir = dirs.Pop();
                    string[] subDirs;
                    try
                    {
                        subDirs = Directory.GetDirectories(currentDir);
                    }

                    catch (UnauthorizedAccessException e)
                    {
                        SW.WriteLine("Нет доступа к файлу или каталогу: " + currentDir);
                        successtask = false;
                        continue;
                    }
                    catch (DirectoryNotFoundException e)
                    {
                        SW.WriteLine("Не найден файл или каталог: " + currentDir);
                        successtask = false;
                        continue;
                    }
                    catch (PathTooLongException e)
                    {
                        SW.WriteLine("Слишком длинный путь или имя файла: " + currentDir);
                        successtask = false;
                        continue;
                    }


                    string[] files = null;
                    try
                    {
                        files = Directory.GetFiles(currentDir);
                    }

                    catch (UnauthorizedAccessException e)
                    {
                        SW.WriteLine(e.Message);
                        successtask = false;
                        continue;
                    }

                    catch (DirectoryNotFoundException e)
                    {
                        SW.WriteLine(e.Message);
                        successtask = false;
                        continue;
                    }

                    if (DTask.Exeption == "no")
                    {
                        foreach (string file in files)
                        {
                            try
                            {
                                FileInfo fi = new FileInfo(file);
                                if (fi.LastWriteTime > DTask.DateBeginBackup)
                                {
                                    zf.AddFile(file, Path.GetDirectoryName(file).Replace(DTask.Source, string.Empty));
                                }
                            }
                            catch (FileNotFoundException e)
                            {
                                SW.WriteLine("Не найден файл: " + file);
                                successtask = false;
                                continue;
                            }

                            catch (PathTooLongException e)
                            {
                                SW.WriteLine("Слишком длинный путь или имя файла: " + file);
                                successtask = false;
                                continue;
                            }
                        }
                    }
                    else
                    {
                        int excludeflag = 0;
                        foreach (string file in files)
                        {
                            try
                            {
                                excludeflag = 0;
                                foreach (var exep in massexeption)
                                {
                                    if (Path.GetFullPath(file).Contains(exep))
                                    {
                                        excludeflag = 1;
                                        break;
                                    }
                                }
                                if (excludeflag == 0)
                                {
                                    FileInfo fi = new FileInfo(file);
                                    if (fi.LastWriteTime > DTask.DateBeginBackup)
                                    {
                                        zf.AddFile(file, Path.GetDirectoryName(file).Replace(DTask.Source, string.Empty));
                                    }
                                }
                            }
                            catch (FileNotFoundException e)
                            {
                                SW.WriteLine("Не найден файл: " + file);
                                successtask = false;
                                continue;
                            }

                            catch (PathTooLongException e)
                            {
                                SW.WriteLine("Слишком длинный путь или имя файла: " + file);
                                successtask = false;
                                continue;
                            }
                        }
                    }


                    foreach (string str in subDirs)
                    {
                        dirs.Push(str);
                    }
                }



                zf.Save();
                zf.Dispose();
                if (successtask)
                {
                    UpdateSosttask(4);
                }
                else
                {
                    UpdateSosttask(5);
                }


                if (DTask.Shadow == 1)
                {
                    foreach (VssSnapshotProperties prop in backup.QuerySnapshots())
                    {
                        if (prop.ExposedName == namedriver)
                        {
                            backup.DeleteSnapshot(prop.SnapshotId, true);
                        }
                    }
                    backup = null;
                }

                string       strLine;
                int          CountSkip    = 0;
                StringReader stringreader = new StringReader(SW.ToString());
                while (true)
                {
                    strLine = stringreader.ReadLine();
                    if (strLine != null)
                    {
                        CountSkip++;
                        BDAL.OpenConnection();
                        BDAL.AddDiffLog(strLine, CurrentDate, DTask.Idtask, 0);
                        BDAL.CloseConnection();
                    }
                    else
                    {
                        break;
                    }
                }


                string       strLine2;
                StringReader stringreader2 = new StringReader(Skip_file_log.ToString());
                while (true)
                {
                    strLine2 = stringreader2.ReadLine();
                    if (strLine2 != null)
                    {
                        if (strLine2.Contains("Skipping"))
                        {
                            CountSkip++;
                            BDAL.OpenConnection();
                            BDAL.AddDiffLog(strLine2, CurrentDate, DTask.Idtask, 0);
                            BDAL.CloseConnection();
                        }
                    }
                    else
                    {
                        break;
                    }
                }


                if (CountSkip > 0)
                {
                    UpdateSosttask(5);
                }

                string msg = "Завершено успешно";

                BDAL.OpenConnection();
                BDAL.AddDiffLog(msg, CurrentDate, DTask.Idtask, 1);
                BDAL.CloseConnection();
                DeleteDimeLive();


                if (DTask.Ftp == 1)
                {
                    try
                    {
                        UpdateSosttask(2);
                        FtpClient    client = new FtpClient();
                        StreamReader sr     = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "ftp_sett.ini");
                        client.PassiveMode = true;   //Включаем пассивный режим.
                        int    TimeoutFTP   = 30000; //Таймаут.
                        string FTP_SERVER   = sr.ReadLine();
                        int    FTP_PORT     = Convert.ToInt32(sr.ReadLine());
                        string FTP_USER     = sr.ReadLine();
                        string FTP_PASSWORD = Decrypt(sr.ReadLine(), "OFRna73");
                        string FTP_FOLDER   = sr.ReadLine();


                        client.Connect(TimeoutFTP, FTP_SERVER, FTP_PORT);
                        client.Login(TimeoutFTP, FTP_USER, FTP_PASSWORD);
                        if (FTP_FOLDER != "not_folder")
                        {
                            client.ChangeDirectory(TimeoutFTP, FTP_FOLDER);
                        }
                        client.PutFile(TimeoutFTP, zf.Name.Substring(zf.Name.IndexOf(DTask.Taskname)), zf.Name);
                        sr.Close();
                        client.Disconnect(TimeoutFTP);

                        msg = "Копирование архива на FTP сервер завершено успешно";

                        BDAL.OpenConnection();
                        BDAL.AddDiffLog(msg, CurrentDate, DTask.Idtask, 1);
                        BDAL.CloseConnection();
                        UpdateSosttask(4);
                    }
                    catch (Exception ex)
                    {
                        BDAL.OpenConnection();
                        BDAL.AddDiffLog(ex.ToString(), CurrentDate, DTask.Idtask, 0);
                        BDAL.CloseConnection();
                        UpdateSosttask(3);
                    }
                }
            }
            catch (Exception ex)
            {
                Add_Diff_Log_Error(ex.Message);
                try
                {
                    if (DTask.Shadow == 1)
                    {
                        foreach (VssSnapshotProperties prop in backup.QuerySnapshots())
                        {
                            if (prop.ExposedName == namedriver)
                            {
                                backup.DeleteSnapshot(prop.SnapshotId, true);
                            }
                        }
                        backup = null;
                    }
                }
                catch
                {
                }
            }
        }
        public void Backup(Tuple <string, string> paths)
        {
            String               _Source1           = paths.Item1;
            String               _Destination       = paths.Item2;
            FileInfo             MyFileInfo         = new FileInfo(_Source1);
            String               _Volume            = MyFileInfo.Directory.Root.Name;
            IVssImplementation   _vssImplementation = VssUtils.LoadImplementation();
            IVssBackupComponents _backup            = _vssImplementation.CreateVssBackupComponents();

            _backup.InitializeForBackup(null);
            _backup.GatherWriterMetadata();
            _backup.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
            _backup.SetBackupState(false, true, Alphaleonis.Win32.Vss.VssBackupType.Full, false);
            Guid MyGuid01 = _backup.StartSnapshotSet();
            Guid MyGuid02 = _backup.AddToSnapshotSet(_Volume, Guid.Empty);

            // VSS step 5: Preparation (Writers & Provaiders need to start preparation)
            _backup.PrepareForBackup();
            // VSS step 6: Create a Snapshot For each volume in the "Snapshot Set"
            _backup.DoSnapshotSet();
            // GET drive labels in use
            var d_name = " ";
            var d_nam  = " ";

            DriveInfo[] allDrives = DriveInfo.GetDrives();
            foreach (DriveInfo d in allDrives)
            {
                if (d.Name != @"A:\")
                {
                    d_name = @"A:\";
                    d_nam  = @"A:";
                }
                else if (d.Name != @"B:\")
                {
                    d_name = @"B:\";
                    d_nam  = @"A:";
                }
                else if (d.Name != @"Z:\")
                {
                    d_name = @"Z:\";
                    d_nam  = @"Z:";
                }
            }
            _backup.ExposeSnapshot(MyGuid02, null, VssVolumeSnapshotAttributes.ExposedLocally, d_nam);
            String sVSSFile1 = _Source1.Replace(_Volume, d_name);

            if (File.Exists(sVSSFile1))
            {
                System.IO.File.Copy(sVSSFile1, _Destination + @"\" + System.IO.Path.GetFileName(_Source1), true);
            }
            foreach (VssSnapshotProperties prop in _backup.QuerySnapshots())
            {
                if (prop.ExposedName == d_name)
                {
                    Console.WriteLine("prop.ExposedNam Found!");
                    _backup.DeleteSnapshot(prop.SnapshotId, true);
                }
            }
            _backup = null;
            return;
        }
Example #6
0
        /// <summary>
        /// This is only first test of using AlphaVSS project.
        /// Please make sure you read thoroughly and understand the code's comments and adapt it to your system and needs.
        /// We are using constant links for "source files to copy" and for the "destination folder".
        /// In any dynamic application you should get those values from the user.
        ///
        /// building your project:
        /// -----------------------
        /// 1. Creating New Project
        ///    * Open Visual Studio As Administrator!
        ///    * Chose create new project type "Console application"
        ///    * use Dot.Net 4 framework
        ///    * named the project Ariely_AlphaVSS_Sample01
        /// 2. Add NuGet Package named alphavss (use the search on-line option, and install the package)
        /// 3. Go over the Code's comment and understand it!!! After you are ready you can use it.
        /// 4. add "using Alphaleonis.Win32.Vss;" & "using System.IO;"
        /// </summary>
        /// <param name="args"></param>
        public static void copy(string destination)
        {
            // Getting information on the files to copy (This is not part of the VSS action)
            string   userName     = Environment.UserName;
            string   baseAddress  = @"C:\Users\{0}\AppData\Local\Microsoft\Windows\WebCache\WebCacheV01.dat";
            string   directory    = string.Format(baseAddress, userName);
            String   _Source1     = directory;
            String   _Destination = destination;
            FileInfo MyFileInfo   = new FileInfo(_Source1);
            String   _Volume      = MyFileInfo.Directory.Root.Name;

            // VSS step 1: Initialize
            IVssImplementation   _vssImplementation = VssUtils.LoadImplementation();
            IVssBackupComponents _backup            = _vssImplementation.CreateVssBackupComponents();

            _backup.InitializeForBackup(null);

            // VSS step 2: Getting Metadata from all the VSS writers
            _backup.GatherWriterMetadata();

            // VSS step 3: VSS Configuration
            _backup.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
            _backup.SetBackupState(false, true, Alphaleonis.Win32.Vss.VssBackupType.Full, false);

            // VSS step 4: Declaring the Volumes that we need to use in this beckup.
            // The Snapshot is a volume element (Here come the name "Volume Shadow-Copy")
            // For each file that we nee to copy we have to make sure that the propere volume is in the "Snapshot Set"
            Guid MyGuid01 = _backup.StartSnapshotSet();
            Guid MyGuid02 = _backup.AddToSnapshotSet(_Volume, Guid.Empty);

            // VSS step 5: Preparation (Writers & Provaiders need to start preparation)
            _backup.PrepareForBackup();
            // VSS step 6: Create a Snapshot For each volume in the "Snapshot Set"
            _backup.DoSnapshotSet();

            /***********************************
             * /* At this point we have a snapshot!
             * /* This action should not take more then 60 second, regardless of file or disk size.
             * /* THe snapshot is not a backup or any copy!
             * /* please more information at http://technet.microsoft.com/en-us/library/ee923636.aspx
             * /***********************************/

            // VSS step 7: Expose Snapshot

            /***********************************
             * /* Snapshot path look like:
             * \\?\Volume{011682bf-23d7-11e2-93e7-806e6f6e6963}\
             * The build in method System.IO.File.Copy do not work with path like this,
             * Therefor, we are going to Expose the Snapshot to our application,
             * by mapping the Snapshot to new virtual volume
             * - Make sure that you are using a volume that is not already exist
             * - This is only for learning purposes. usually we will use the snapshot directly as i show in the next example in the blog
             * /***********************************/
            _backup.ExposeSnapshot(MyGuid02, null, VssVolumeSnapshotAttributes.ExposedLocally, "S:");

            // VSS step 8: Copy Files!

            /***********************************
             * /* Now we start to copy the files/folders/disk!
             * /* Execution time can depend on what we are copying
             * /* We can copy one element or several element.
             * /* As long as we are working under the same snapshot,
             * /* the element should be in consist state from the same point-in-time
             * /***********************************/
            String sVSSFile1 = _Source1.Replace(_Volume, @"S:\");

            if (File.Exists(sVSSFile1))
            {
                System.IO.File.Copy(sVSSFile1, _Destination + @"\" + System.IO.Path.GetFileName(_Source1), true);
            }


            // VSS step 9: Delete the snapshot (using the Exposed Snapshot name)
            foreach (VssSnapshotProperties prop in _backup.QuerySnapshots())
            {
                if (prop.ExposedName == @"S:\")
                {
                    Console.WriteLine("prop.ExposedNam Found!");
                    _backup.DeleteSnapshot(prop.SnapshotId, true);
                }
            }

            _backup = null;
        }
Example #7
0
        public bool Create(List<String> Volumes)
        {
            try
            {
                if (OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.X64 || OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.IA64)
                {
                    if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\AlphaVSS.60.x64.dll"))
                    {
                        HelperFunctions.ShowError(Translations.Get("WrongVersion64"));
                        Settings.ShadowCopy = false;
                        return false;
                    }
                }
                else
                {
                    if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\AlphaVSS.60.x86.dll"))
                    {
                        HelperFunctions.ShowError(Translations.Get("WrongVersion32"));
                        Settings.ShadowCopy = false;
                        return false;
                    }
                }
                if (GlobalData.SettingsInAppData)
                {
                    _OldSnapshotSetIdsPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\RoboGapp\\SnapshotIds.dat";
                }
                else
                {
                    _OldSnapshotSetIdsPath = System.Windows.Forms.Application.StartupPath + "\\SnapshotIds.dat";
                }
                Abort();
                HelperFunctions.WriteLog(Translations.Get("LoadingVSSImplementation"));
                IVssImplementation VssImplementation = null;
                try
                {
                    VssImplementation = VssUtils.LoadImplementation();
                }
                catch (Exception ex)
                {
                    HelperFunctions.ShowError(Translations.Get("ShadowCopyError") + "\n\n" + Translations.Get("Error") + "\n" + ex.Message);
                    if (OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.X64)
                    {
                        HelperFunctions.ShowError(Translations.Get("VCRedist64"));
                    }
                    else if (OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.IA64)
                    {
                        HelperFunctions.ShowError(Translations.Get("VCRedistIA64"));
                    }
                    else
                    {
                        HelperFunctions.ShowError(Translations.Get("VCRedist32"));
                    }
                    return false;
                }
                HelperFunctions.WriteLog(Translations.Get("CreatingBackupComponents"));
                _BackupComponents = VssImplementation.CreateVssBackupComponents();
                HelperFunctions.WriteLog(Translations.Get("InitializingVSSBackup"));
                _BackupComponents.InitializeForBackup(null);
                if (OperatingSystemInfo.OSVersionName > OSVersionName.WindowsServer2003)
                {
                    HelperFunctions.WriteLog(Translations.Get("SettingVSSContext"));
                    _BackupComponents.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
                }
                HelperFunctions.WriteLog(Translations.Get("SettingVSSBackupState"));
                _BackupComponents.SetBackupState(false, true, VssBackupType.Full, false);
                HelperFunctions.WriteLog(Translations.Get("GatheringWriterMetadata"));
                _BackupComponents.GatherWriterMetadata();

                HelperFunctions.WriteLog(Translations.Get("CreatingSnapshotSet"));
                _SnapshotSetId = _BackupComponents.StartSnapshotSet();
                _SnapshotIds.Clear();
                for (int i = 0; i < Volumes.Count; i++)
                {
                    HelperFunctions.WriteLog(Translations.Get("AddingToSnapshotSet1") + Volumes[i] + Translations.Get("AddingToSnapshotSet2"));
                    Guid SnapshotId = _BackupComponents.AddToSnapshotSet(Volumes[i], Guid.Empty);
                    _SnapshotIds.Add(SnapshotId);
                }
                HelperFunctions.WriteLog(Translations.Get("SavingSnapshotSetID"));
                SaveSnapshotSetId();

                HelperFunctions.WriteLog(Translations.Get("PreparingVSSBackup"));
                _BackupComponents.PrepareForBackup();

                HelperFunctions.WriteLog(Translations.Get("CreatingVSSSnapshots"));
                _BackupComponents.DoSnapshotSet();

                HelperFunctions.WriteLog(Translations.Get("ExposingSnapshots"));
                GlobalData.ShadowCopyMounts.Clear();
                List<String> FreeDriveLetters = IO.GetFreeDriveLetters();

                String Path = System.Windows.Forms.Application.StartupPath;
                if (OperatingSystemInfo.OSVersionName > OSVersionName.WindowsServer2003)
                {
                    try
                    {
                        if (System.IO.File.Exists(Path + "\\write.test")) File.Delete(Path + "\\write.test");
                        using (System.IO.File.Create(Path + "\\write.test")) { }
                        File.Delete(Path + "\\write.test");
                    }
                    catch
                    {
                        Path = IO.GetCommonApplicationDataPath();
                        if (Path == "")
                        {
                            HelperFunctions.ShowError(Translations.Get("ExposingSnapshotsDirError"));
                            return false;
                        }
                    }
                }
                for (int i = 0; i < Volumes.Count; i++)
                {
                    if (OperatingSystemInfo.OSVersionName <= OSVersionName.WindowsServer2003)
                    {
                        GlobalData.ShadowCopyMounts.Add(Volumes[i], FreeDriveLetters[i]);
                        DefineDosDevice(0, FreeDriveLetters[i].Substring(0, 2), _BackupComponents.GetSnapshotProperties(_SnapshotIds[i]).SnapshotDeviceObject);
                    }
                    else
                    {
                        DriveInfo DriveInfo = null;
                        if (Path == System.Windows.Forms.Application.StartupPath)
                        {
                            DriveInfo = DriveInfo.GetDrives().FirstOrDefault((DriveInfo DI) => DI.RootDirectory.ToString() == System.Windows.Forms.Application.StartupPath.Substring(0, 3));
                            if (DriveInfo == null || DriveInfo.DriveType == DriveType.Network)
                            {
                                Path = IO.GetCommonApplicationDataPath();
                                if (Path == "")
                                {
                                    HelperFunctions.ShowError(Translations.Get("ExposingSnapshotsDirError"));
                                    return false;
                                }
                            }
                        }
                        GlobalData.ShadowCopyMounts.Add(Volumes[i], Path + "\\mnt" + i.ToString() + "\\");
                        if (System.IO.Directory.Exists(GlobalData.ShadowCopyMounts[Volumes[i]]))
                        {
                            try
                            {
                                Directory.Delete(GlobalData.ShadowCopyMounts[Volumes[i]], false);
                            }
                            catch (Exception ex)
                            {
                                HelperFunctions.ShowError(ex);
                                return false;
                            }
                        }
                        Directory.Create(GlobalData.ShadowCopyMounts[Volumes[i]]);
                        _BackupComponents.ExposeSnapshot(_SnapshotIds[i], null, VssVolumeSnapshotAttributes.ExposedLocally, GlobalData.ShadowCopyMounts[Volumes[i]]);
                    }
                }
                HelperFunctions.WriteLog(Translations.Get("SnapshotSuccessful"));
                return true;
            }
            catch (Exception ex)
            {
                HelperFunctions.ShowError(ex);
                return false;
            }
        }