コード例 #1
0
        private void CreateVssSnapshotOfSystemVolume(IVssBackupComponents backupComponents)
        {
            try
            {
                logger.LogInformation($"Creating VSS snapshot for drive {migrationData.OperatingSystemDriveLetter}:\\");
                backupComponents.InitializeForBackup(null);
                backupComponents.GatherWriterMetadata();
                backupComponents.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);

                this.vssSnapshotSetId = backupComponents.StartSnapshotSet();

                this.vssSnapshotId = backupComponents.AddToSnapshotSet($"{migrationData.OperatingSystemDriveLetter}:\\");
                backupComponents.SetBackupState(false, true, VssBackupType.Differential, false);
                backupComponents.PrepareForBackup();
                backupComponents.DoSnapshotSet();

                VssSnapshotProperties snapshotInfo = backupComponents.GetSnapshotProperties(this.vssSnapshotId);
                logger.LogDebug($"VSS snapshot created. Root Path: {snapshotInfo.SnapshotDeviceObject}");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "An error occured during VSS snapshot creation");
                if (this.vssSnapshotId != Guid.Empty)
                {
                    backupComponents.DeleteSnapshot(this.vssSnapshotId, true);
                    this.vssSnapshotId    = Guid.Empty;
                    this.vssSnapshotSetId = Guid.Empty;
                }
                throw;
            }
        }
コード例 #2
0
        public void Delete(ISnapshot sn)
        {
            Logger.Append(Severity.DEBUG, "Deleting snapshot " + sn.Path + " (id " + sn.Id + ")");
            if (!OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
            {
                // Deleting is unnecessary on XP since snaps are non-persistent
                // and automatically released on Disposing VSS objects.
                return;
            }


            try{
                IVssImplementation vssi = VssUtils.LoadImplementation();
                using (IVssBackupComponents oVSS = vssi.CreateVssBackupComponents()){
                    oVSS.InitializeForBackup(null);
                    oVSS.SetContext(VssSnapshotContext.All);
                    oVSS.DeleteSnapshot(sn.Id, true);
                }

                Logger.Append(Severity.INFO, "Deleted snapshot " + sn.Path + " (id " + sn.Id + ")");
            }
            catch (Exception vsse) {
                Logger.Append(Severity.WARNING, "Unable to delete snapshot " + sn.Path + " (id " + sn.Id + "): " + vsse.Message);
                //backup.Dispose();
                throw vsse;
            }
        }
コード例 #3
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;
        }
コード例 #4
0
        public void Dispose()
        {
            try
            {
                if (_mappedDrives != null)
                {
                    foreach (var d in _mappedDrives)
                    {
                        d.Dispose();
                    }

                    _mappedDrives = null;
                }
            }
            catch (Exception ex)
            {
                Logging.Log.WriteVerboseMessage(LOGTAG, "MappedDriveCleanupError", ex, "Failed during VSS mapped drive unmapping");
            }

            try
            {
                _vssBackupComponents?.BackupComplete();
            }
            catch (Exception ex)
            {
                Logging.Log.WriteVerboseMessage(LOGTAG, "VSSTerminateError", ex, "Failed to signal VSS completion");
            }

            try
            {
                if (_vssBackupComponents != null)
                {
                    foreach (var g in _volumes.Values)
                    {
                        try
                        {
                            _vssBackupComponents.DeleteSnapshot(g, false);
                        }
                        catch (Exception ex)
                        {
                            Logging.Log.WriteVerboseMessage(LOGTAG, "VSSSnapShotDeleteError", ex, "Failed to close VSS snapshot");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log.WriteVerboseMessage(LOGTAG, "VSSSnapShotDeleteCleanError", ex, "Failed during VSS esnapshot closing");
            }

            if (_vssBackupComponents != null)
            {
                _vssBackupComponents.Dispose();
                _vssBackupComponents = null;
            }
        }
コード例 #5
0
        private void RemoveVssSnapshotOfSystemVolume(IVssBackupComponents backupComponents)
        {
            if (this.vssSnapshotId != Guid.Empty)
            {
                try
                {
                    backupComponents.BackupComplete();
                }
                catch (VssBadStateException) { }

                VssSnapshotProperties snapshotInfo = backupComponents.GetSnapshotProperties(this.vssSnapshotId);

                logger.LogDebug($"Removing snapshot {snapshotInfo.SnapshotDeviceObject}");
                backupComponents.DeleteSnapshot(this.vssSnapshotId, true);
            }
        }
コード例 #6
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
            GC.SuppressFinalize(this);

            if (_backup == null)
            {
                return;
            }

            if (_shadowCopyId != Guid.Empty)
            {
                Helpers.ExecSafe(() => _backup.DeleteSnapshot(_shadowCopyId, true));
            }

            Helpers.Dispose(ref _backup);
            _snapshotVolumeName = null;
            _snapshotSetId      = Guid.Empty;
        }
コード例 #7
0
ファイル: AddonsBackup.cs プロジェクト: catontheway/AxTools
        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();
            }
        }
コード例 #8
0
        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                try
                {
                    if (m_mappedDrives != null)
                    {
                        foreach (var d in m_mappedDrives)
                        {
                            d.Dispose();
                        }

                        m_mappedDrives = null;
                    }
                }
                catch (Exception ex)
                {
                    Logging.Log.WriteVerboseMessage(LOGTAG, "MappedDriveCleanupError", ex, "Failed during VSS mapped drive unmapping");
                }

                try
                {
                    m_backup?.BackupComplete();
                }
                catch (Exception ex)
                {
                    Logging.Log.WriteVerboseMessage(LOGTAG, "VSSTerminateError", ex, "Failed to signal VSS completion");
                }

                try
                {
                    if (m_backup != null)
                    {
                        foreach (var g in m_volumes.Values)
                        {
                            try
                            {
                                m_backup.DeleteSnapshot(g, false);
                            }
                            catch (Exception ex)
                            {
                                Logging.Log.WriteVerboseMessage(LOGTAG, "VSSSnapShotDeleteError", ex, "Failed to close VSS snapshot");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.Log.WriteVerboseMessage(LOGTAG, "VSSSnapShotDeleteCleanError", ex, "Failed during VSS esnapshot closing");
                }

                if (m_backup != null)
                {
                    m_backup.Dispose();
                    m_backup = null;
                }
            }

            base.Dispose(disposing);
        }
コード例 #9
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
                {
                }
            }
        }
コード例 #10
0
        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;
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: zhaokk/bhv
        /// <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;
        }