public void TestInvalidDriveName()
 {
     var invalidDrive = new DriveInfo("NonExistentDriveName");
     Assert.Throws<DriveNotFoundException>(() => { var df = invalidDrive.DriveFormat; });
     Assert.Throws<DriveNotFoundException>(() => { var size = invalidDrive.DriveType; });
     Assert.Throws<DriveNotFoundException>(() => { var size = invalidDrive.TotalFreeSpace; });
     Assert.Throws<DriveNotFoundException>(() => { var size = invalidDrive.TotalSize; });
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DriveInfoWrapper"/> class, which acts as a wrapper for a drive info.
        /// </summary>
        /// <param name="instance">The drive info.</param>
        public DriveInfoWrapper(DriveInfo instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            this.instance = instance;
        }
 public void TestProperties()
 {
     var root = new DriveInfo("/");
     Assert.Equal("/", root.Name);
     Assert.Equal("/", root.RootDirectory.FullName);
     Assert.Equal(DriveType.Fixed, root.DriveType);
     Assert.True(root.IsReady);
     Assert.True(root.AvailableFreeSpace > 0);
     Assert.True(root.TotalFreeSpace > 0);
     Assert.True(root.TotalSize > 0);
 }
    public static Node CreateDrive(DriveInfo driveInfo)
    {
        var driveNode = new Node()
        {
            Name = driveInfo.Name,
            Path = driveInfo.RootDirectory.FullName,
            Parent = null,
            Type = Node.DriveTypeName
        };

        return driveNode;
    }
Exemple #5
0
        public uint GetDriveInfo(uint nRobotID, ref DriveInfo myDriveInfo)
        {
            uint nValue = 0;
            try
            {
                nValue = PTRobot_GetDriveInfo(nRobotID, myDriveInfo);
            }
            catch (Exception e)
            {
                MessageBox.Show("PTRobot_GetDriveInfo() failed:\n" + e.Message);
            }

            return nValue;
        }
 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);
 }
 public static List<DriveInfo> GetDrives(this DriveInfo drive,
         DriveType type)
 {
     List<DriveInfo> list = new List<DriveInfo>();
         foreach (string s in DriveInfoX.DefaultInstance.GetATOZLetters())
         {
             DriveInfo newDrive = new DriveInfo(s);
             DirectoryInfo di = newDrive.RootDirectory;
             if(drive.DriveType == type && di.Exists)
             {
                 list.Add(newDrive);
             }
         }
         return list;
 }
        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
        }
Exemple #9
0
    public JSONFSData(DriveInfo Drive)
    {
        Name = Drive.Name;
        Label = Drive.VolumeLabel;
        Format = Drive.DriveFormat;

        // Bytes to MB
        Size = Drive.TotalSize / (1024 * 1024);
        Free = Drive.TotalFreeSpace / (1024 * 1024);

        // Round
        Size = Math.Round(Size, 2, MidpointRounding.ToEven);
        Free = Math.Round(Free, 2, MidpointRounding.ToEven);

        // MB to GB and round
        Size = Math.Round(Size / 1024, 1, MidpointRounding.ToEven);
        Free = Math.Round(Free / 1024, 1, MidpointRounding.ToEven);
    }
        private void GetSerialNumberDriveInfo(int index = 0)
        {

            TextBoxDisque.Clear();

            this._stopWatch.Start();
            DriveInfo info = new DriveInfo(index);
            LogMethodExcecutionTime("GetSerialNumberDriveInfo");

            if ((info.SerialNumber != null))
            {
                TextBoxDisque.AppendText(info.SerialNumber.ToString() + "\r\n");
                TextBoxDisque.AppendText(info.Model.ToString() + "\r\n");
                TextBoxDisque.AppendText(info.DriveType.ToString() + "\r\n");
                TextBoxDisque.AppendText(info.Firmware.ToString() + "\r\n");
                return;
            }
            TextBoxDisque.AppendText("No serial number");

        }
Exemple #11
0
        public bool AddDrive(DriveInfo drive, string password)
        {
            foreach (DriveInfo dInfo in DrivesList)
            {
                if (dInfo.Root == drive.Root ||
                    dInfo.Letter == drive.Letter)
                {
                    return false;
                }
            }

            Directory.CreateDirectory(drive.Root);

            CreateDriveSettings(drive, password);

            MountDrive(drive);
            appSettings.AddDrive(drive);

            return true;
        }
        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();
        }
        public bool ChangePassword(DriveInfo drive, string oldPassword, string newPassword)
        {
            if (ValidPassword(drive))
            {
                string password = GetDrivePassword(drive);

                if (password == oldPassword)
                {
                    XmlDriveSettings dSettings = new XmlDriveSettings(drive.Root);

                    byte[] encPassword = encryptor.EnDecrypt(true, Encoding.Default.GetBytes(newPassword));
                    password = Encoding.Default.GetString(encPassword);
                    dSettings.WritePassword(password);

                    string md5Password = GetMd5Hash(newPassword);
                    dSettings.WriteMd5Password(md5Password);

                    return true;
                }
            }

            return false;
        }
        public void AddDrive(DriveInfo drive)
        {
            XmlNode driveNode = xmlDoc.CreateElement(driveElem);

            XmlNode letterNode = xmlDoc.CreateElement(letterElem);
            letterNode.InnerText = drive.Letter.ToString(); ;
            driveNode.AppendChild(letterNode);

            XmlNode labelNode = xmlDoc.CreateElement(labelElem);
            labelNode.InnerText = drive.Label;
            driveNode.AppendChild(labelNode);

            XmlNode rootNode = xmlDoc.CreateElement(rootElem);
            rootNode.InnerText = drive.Root;
            driveNode.AppendChild(rootNode);

            XmlNode mountedNode = xmlDoc.CreateElement(mountedElem);
            mountedNode.InnerText = drive.Mounted ? mountedDrive.ToString() : emptyElemValue;
            driveNode.AppendChild(mountedNode);

            xmlDoc.DocumentElement.AppendChild(driveNode);
            xmlDoc.Save(settingsFile);
        }
Exemple #15
0
 public DriveLetterItem(DriveInfo info)
 {
     this.info = info;
 }
 public bool UnMountDrive(DriveInfo drive, bool forMount)
 {
     foreach (XmlNode table in xmlDoc.DocumentElement.ChildNodes)
     {
         string root = string.Empty;
         foreach (XmlNode ch in table.ChildNodes)
         {
             if (ch.Name == rootElem)
             {
                 root = ch.InnerText;
                 break;
             }
         }
         if (drive.Root == root)
         {
             foreach (XmlNode ch in table.ChildNodes)
             {
                 if (ch.Name == mountedElem)
                 {
                     ch.InnerText = forMount ? mountedDrive.ToString() : emptyElemValue;
                     break;
                 }
             }
             xmlDoc.Save(settingsFile);
             return true;
         }
     }
     return false;
 }
Exemple #17
0
        private void buttonRipWave_Click(object sender, EventArgs e)
        {
            buttonRipWave.Enabled = false;
            _cancel = false;
            bool runningOnWindows = !(Configuration.IsRunningOnLinux() || Configuration.IsRunningOnMac());

            SourceVideoFileName = labelVideoFileName.Text;
            string targetFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".wav");

            labelPleaseWait.Visible = true;
            Process process;

            try
            {
                string encoderName;
                process        = GetCommandLineProcess(SourceVideoFileName, _audioTrackNumber, targetFile, _encodeParamters, out encoderName);
                labelInfo.Text = encoderName;
            }
            catch (DllNotFoundException)
            {
                if (MessageBox.Show(Configuration.Settings.Language.AddWaveform.VlcMediaPlayerNotFound + Environment.NewLine +
                                    Environment.NewLine +
                                    Configuration.Settings.Language.AddWaveform.GoToVlcMediaPlayerHomePage,
                                    Configuration.Settings.Language.AddWaveform.VlcMediaPlayerNotFoundTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    Process.Start("http://www.videolan.org/");
                }
                buttonRipWave.Enabled = true;
                return;
            }

            process.Start();
            progressBar1.Style   = ProgressBarStyle.Marquee;
            progressBar1.Visible = true;
            double seconds = 0;

            buttonCancel.Visible = true;
            try
            {
                process.PriorityClass = ProcessPriorityClass.Normal;
            }
            catch
            {
            }
            while (!process.HasExited)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(100);
                seconds += 0.1;
                if (seconds < 60)
                {
                    labelProgress.Text = string.Format(Configuration.Settings.Language.AddWaveform.ExtractingSeconds, seconds);
                }
                else
                {
                    labelProgress.Text = string.Format(Configuration.Settings.Language.AddWaveform.ExtractingMinutes, (int)(seconds / 60), (int)(seconds % 60));
                }
                Refresh();
                if (_cancel)
                {
                    process.Kill();
                    progressBar1.Visible    = false;
                    labelPleaseWait.Visible = false;
                    buttonRipWave.Enabled   = true;
                    buttonCancel.Visible    = false;
                    DialogResult            = DialogResult.Cancel;
                    return;
                }

                if (seconds > 1 && Convert.ToInt32(seconds) % 10 == 0 && runningOnWindows)
                {
                    try
                    {
                        var drive = new DriveInfo("c");
                        if (drive.IsReady)
                        {
                            if (drive.AvailableFreeSpace < 50 * 1000000) // 50 mb
                            {
                                labelInfo.ForeColor = Color.Red;
                                labelInfo.Text      = "LOW DISC SPACE!";
                            }
                            else if (labelInfo.ForeColor == Color.Red)
                            {
                                labelInfo.Text = Utilities.FormatBytesToDisplayFileSize(drive.AvailableFreeSpace) + " free";
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            buttonCancel.Visible = false;
            progressBar1.Visible = false;
            progressBar1.Style   = ProgressBarStyle.Blocks;
            process.Dispose();

            if (!File.Exists(targetFile))
            {
                if (_encodeParamters != RetryEncodeParameters)
                {
                    _encodeParamters = RetryEncodeParameters;
                    buttonRipWave_Click(null, null);
                    return;
                }

                MessageBox.Show("Could not find extracted wave file! This feature requires VLC media player 1.1.x or newer (" + (IntPtr.Size * 8) + " -bit)." + Environment.NewLine
                                + Environment.NewLine +
                                "Command line: " + process.StartInfo.FileName + " " + process.StartInfo.Arguments);

                labelPleaseWait.Visible = false;
                labelProgress.Text      = string.Empty;
                buttonRipWave.Enabled   = true;
                return;
            }

            var fi = new FileInfo(targetFile);

            if (fi.Length <= 200)
            {
                MessageBox.Show("Sorry! VLC/FFmpeg was unable to extract audio to wave file via this command line:" + Environment.NewLine +
                                Environment.NewLine +
                                "Command line: " + process.StartInfo.FileName + " " + process.StartInfo.Arguments + Environment.NewLine +
                                Environment.NewLine +
                                "Note: Do check free disk space.");
                labelPleaseWait.Visible = false;
                labelProgress.Text      = string.Empty;
                buttonRipWave.Enabled   = true;
                return;
            }

            ReadWaveFile(targetFile, _delayInMilliseconds);
            labelProgress.Text = string.Empty;
            File.Delete(targetFile);
            DialogResult = DialogResult.OK;
        }
        private void GetObjectPropsUnscaled(string strPath, DriveInfo drvHint,
                                            out Image img, ref string strDisplayName)
        {
            img = null;

            try
            {
                string strName;
                NativeMethods.SHGetFileInfo(strPath, m_nIconDim, out img,
                                            out strName);

                if (!string.IsNullOrEmpty(strName) && (strName.IndexOf(
                                                           Path.DirectorySeparatorChar) < 0))
                {
                    strDisplayName = strName;
                }

                if (img != null)
                {
                    return;
                }
            }
            catch (Exception) { Debug.Assert(false); }

            ImageList.ImageCollection icons = Program.MainForm.ClientIcons.Images;

            if ((strPath.Length <= 3) && (drvHint != null))
            {
                switch (drvHint.DriveType)
                {
                case DriveType.Fixed:
                    img = new Bitmap(icons[(int)PwIcon.Drive]);
                    break;

                case DriveType.CDRom:
                    img = new Bitmap(icons[(int)PwIcon.CDRom]);
                    break;

                case DriveType.Network:
                    img = new Bitmap(icons[(int)PwIcon.NetworkServer]);
                    break;

                case DriveType.Ram:
                    img = new Bitmap(icons[(int)PwIcon.Memory]);
                    break;

                case DriveType.Removable:
                    img = new Bitmap(icons[(int)PwIcon.Disk]);
                    break;

                default:
                    img = new Bitmap(icons[(int)PwIcon.Folder]);
                    break;
                }

                return;
            }

            img = UIUtil.GetFileIcon(strPath, m_nIconDim, m_nIconDim);
            if (img != null)
            {
                return;
            }

            if (Directory.Exists(strPath))
            {
                img = new Bitmap(icons[(int)PwIcon.Folder]);
                return;
            }
            if (File.Exists(strPath))
            {
                img = new Bitmap(icons[(int)PwIcon.PaperNew]);
                return;
            }

            Debug.Assert(false);
            img = new Bitmap(icons[(int)PwIcon.Star]);
        }
Exemple #19
0
        private void UserControl1_Load(object sender, EventArgs e)
        {
            if (a == 0)
            {
                #region MOBO e CPU
                MBlbl.Text = HardwareInfo.getmoboInfo() + HardwareInfo.getbeiosver();

                CPUlbl.Text = HardwareInfo.getcpuinfo();

                ramBox.Text  = "";
                dskBox.Text  = "";
                moboBox.Text = "";
                gpuBox.Text  = "";
                cpuBox.Text  = "";

                #endregion

                #region RAM

                try
                { RAMlbl.Text = "Total: " + HardwareInfo.GetPhysicalMemory() + HardwareInfo.getmeminfo() + HardwareInfo.getmeminfo2(); }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "WMI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Console.SetOut(new TextBoxWriter(ramBox));
                ConnectionOptions connection = new ConnectionOptions();
                connection.Impersonation = ImpersonationLevel.Impersonate;
                ManagementScope scope = new ManagementScope("\\root\\CIMV2", connection);
                scope.Connect();
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_PhysicalMemory");
                ManagementObjectSearcher   searcher = new ManagementObjectSearcher(scope, query);
                ManagementObjectCollection allmem   = searcher.Get();
                long memsz  = 0;
                long memfsz = 0;
                foreach (ManagementObject onemem in allmem)
                {
                    memsz  = Convert.ToInt64(onemem["Capacity"]);
                    memfsz = ((memsz / 1024) / 1024) / 1024;
                    Console.WriteLine("Slot: {0}   Modelo: {1} {2}   Tamanho: {3}GB",
                                      onemem["DeviceLocator"], onemem["Manufacturer"], onemem["Model"], memfsz.ToString());
                }

                #endregion

                #region DSK

                try
                {
                    Console.SetOut(new TextBoxWriter(dskBox));

                    ManagementScope            scope2    = new ManagementScope(@"\\localhost\ROOT\Microsoft\Windows\Storage");
                    ObjectQuery                query2    = new ObjectQuery("SELECT * FROM MSFT_PhysicalDisk");
                    ManagementObjectSearcher   searcher2 = new ManagementObjectSearcher(scope2, query2);
                    ManagementObjectCollection allPDisks = searcher2.Get();
                    long   dsktp     = 0;
                    long   drvtp     = 0;
                    long   dskhealth = 0;
                    string dsktype   = "Outro";
                    string dskhlt    = "Desconhecido";

                    foreach (ManagementObject onePDisk in allPDisks)
                    {
                        dsktp     = Convert.ToInt64(onePDisk["BusType"]);
                        drvtp     = Convert.ToInt64(onePDisk["MediaType"]);
                        dskhealth = Convert.ToInt64(onePDisk["HealthStatus"]);
                        if (dsktp == 7)
                        {
                            dsktype = "USB";
                        }
                        if (dsktp == 8)
                        {
                            dsktype = "SCSI";
                        }
                        if (dsktp == 12)
                        {
                            dsktype = "SD";
                        }
                        if (dsktp == 13)
                        {
                            dsktype = "MMC";
                        }
                        if (dsktp == 11)
                        {
                            if (drvtp == 4)
                            {
                                dsktype = "SSD SATA";
                            }
                            else
                            {
                                dsktype = "SATA HD";
                            }
                        }
                        if (dsktp == 17)
                        {
                            dsktype = "SSD NVMe";
                        }
                        if (dskhealth == 0)
                        {
                            dskhlt = "Boa";
                        }
                        if (dskhealth == 1)
                        {
                            dskhlt = "ALERTA!";
                        }
                        if (dskhealth == 2)
                        {
                            dskhlt = "RUIM!!!";
                        }
                        Console.WriteLine("{0}" + "\t" + "{1}" + "\t" + "{2}" + "\t" + "{3}", "Disco: " + onePDisk["DeviceId"], "Modelo: " + onePDisk["Model"], "Tipo: " + dsktype, "Saúde: " + dskhlt);
                    }
                    Console.WriteLine("");
                    long        vlmax       = 0;
                    long        vlcrt       = 0;
                    long        szmax       = 0;
                    long        szcrt       = 0;
                    string      driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
                    DriveInfo[] allDrives   = DriveInfo.GetDrives();
                    foreach (DriveInfo d in allDrives)
                    {
                        if (d.IsReady == true)
                        {
                            vlmax = Convert.ToInt64(d.TotalSize);
                            vlcrt = Convert.ToInt64(d.TotalFreeSpace);
                            szmax = ((vlmax / 1024) / 1024) / 1024;
                            szcrt = ((vlcrt / 1024) / 1024) / 1024;
                            if (d.Name != driveLetter)
                            {
                                if (szmax != 20)
                                {
                                    Console.WriteLine("Volume: {0}" + "\t" + "Total: {1}GB" + "\t" + "Livres: {2}GB" + "\t" + "Formato: {3}", d.Name, szmax, szcrt, d.DriveFormat);
                                }
                            }
                        }
                    }
                }
                catch (Exception dskex)
                { MessageBox.Show(dskex.Message, "Erro ao obter informações", MessageBoxButtons.OK, MessageBoxIcon.Error); }

                #endregion

                #region GPU

                Console.SetOut(new TextBoxWriter(gpuBox));
                ManagementObjectSearcher gpuinfo = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
                string gpu  = string.Empty;
                int    vram = 0;
                foreach (ManagementObject mo in gpuinfo.Get())
                {
                    PropertyData description = mo.Properties["Description"];
                    if (description != null)
                    {
                        gpu = ((string)(description.Value));
                        gpu = gpu.Replace("(TM)", "").Replace("(tm)", "").Replace("™", "").Replace("®", "").Replace("(R)", "").Replace("(r)", "").Replace("©", "").Replace("(C)", "").Replace("(c)", "")
                              .Replace("    ", " ").Replace("  ", " ").Replace("Express", "").Replace("Chipset", "").Replace("Microsoft", "").Replace("Corporation", "").Replace("(", "")
                              .Replace(")", "").Replace("WDDM", "").Replace("WDM", "");
                    }
                }
                ManagementObjectSearcher vramS = new ManagementObjectSearcher("select AdapterRAM from Win32_VideoController");

                foreach (ManagementObject rg in vramS.Get())
                {
                    var gpram = rg.Properties["AdapterRAM"].Value as UInt32?;

                    if (gpram.HasValue)
                    {
                        vram = ((int)gpram / 1048576);
                    }
                }
                string bus  = "";
                string clVR = "";
                string clBG = "";
                string clAG = "";
                string tGPU = "";
                string tVR  = "";
                string RPM  = "";

                if (gpu.Contains("AMD") == true)
                {
                    foreach (var hardwareItem in thisComputer.Hardware)
                    {
                        if (hardwareItem.HardwareType == HardwareType.GpuAti)
                        {
                            hardwareItem.Update();
                            foreach (IHardware subHardware in hardwareItem.SubHardware)
                            {
                                subHardware.Update();
                            }
                            foreach (var sensor in hardwareItem.Sensors)
                            {
                                if (sensor.SensorType == SensorType.Temperature)
                                {
                                    tGPU = sensor.Value.Value.ToString();
                                }

                                if (sensor.SensorType == SensorType.Clock)
                                {
                                    clAG = sensor.Value.Value.ToString();
                                }
                            }
                        }
                    }
                    Console.WriteLine("Nome: {0}" + "\t" + "BUS: {1}bits" + "\n" + "Capacidade VRAM: {2}GB" + "\t" + "Clock VRAM: {3}Mhz" + "\n" +
                                      "Clock Base GPU: {4}Mhz" + "\t" + "Clock Atual GPU: {5}Mhz" + "\n" + "Temp. GPU: {6}°C" + "\t" + "Temp. VRAM: {7}°C" + "\t" +
                                      "Velocidade FAN: {8}RPM", gpu, bus, vram.ToString(), clVR, clBG, clAG, tGPU, tVR, RPM);
                }

                if (gpu.Contains("Nvidia") == true)
                {
                    foreach (var hardwareItem in thisComputer.Hardware)
                    {
                        if (hardwareItem.HardwareType == HardwareType.GpuNvidia)
                        {
                            hardwareItem.Update();
                            foreach (IHardware subHardware in hardwareItem.SubHardware)
                            {
                                subHardware.Update();
                            }
                            foreach (var sensor in hardwareItem.Sensors)
                            {
                                if (sensor.SensorType == SensorType.Temperature)
                                {
                                    tGPU = sensor.Value.Value.ToString();
                                }

                                if (sensor.SensorType == SensorType.Clock)
                                {
                                    clAG = sensor.Value.Value.ToString();
                                }
                            }
                        }
                    }
                    Console.WriteLine("Nome: {0}" + "\t" + "BUS: {1}bits" + "\n" + "Capacidade VRAM: {2}GB" + "\t" + "Clock VRAM: {3}Mhz" + "\n" +
                                      "Clock Base GPU: {4}Mhz" + "\t" + "Clock Atual GPU: {5}Mhz" + "\n" + "Temp. GPU: {6}°C" + "\t" + "Temp. VRAM: {7}°C" + "\t" +
                                      "Velocidade FAN: {8}RPM", gpu, bus, vram.ToString(), clVR, clBG, clAG, tGPU, tVR, RPM);
                }

                if (gpu.Contains("Intel") == true)
                {
                    Console.WriteLine("Nome: {0}" + "\t" + "\n" + "Capacidade VRAM: {1}GB" + "\t" + "Clock Base GPU: {2}Mhz" +
                                      "\n" + "Clock Atual GPU: {3}Mhz" + "\n" + "Temp. GPU: {4}°C", gpu, vram.ToString(), clBG, tGPU);
                }


                #endregion

                a = 1;
            }
        }
        public bool RemoveDrive(DriveInfo drive)
        {
            if (ValidPassword(drive))
            {
                UnmountDrive(drive);
                appSettings.RemoveDrive(drive);
                DrivesList = appSettings.GetDrives();
                return true;
            }

            return false;
        }
        /// <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;
        }
Exemple #22
0
 public static IEnumerable <DriveInfo> GetAllFixedNtfsDrives()
 {
     return(DriveInfo.GetDrives()
            .Where(d => d.DriveType == DriveType.Fixed && d.DriveFormat.ToUpper() == "NTFS"));
 }
Exemple #23
0
        private async void StreamThread()
        {
            foreach (var item in token)
            {
                Authentication.TokenResult appToken = null;
                if (item.Token.Drive == "Google")
                {
                    appToken = await WebAuthorization.RedeemAuthorizationCodeAsync(Client.GoogleClientID, UriCollection.GoogleinstalledAppRedirectUri, Client.GoogleClientSecret,
                                                                                   item.Token.refresh_token, UriCollection.GoogleTokenUri, "refresh_token", WebAuthorization.TokenOption.REFRESHTOKEN);

                    appToken.refresh_token = item.Token.refresh_token;
                    appToken.Drive         = item.Token.Drive;
                }
                else if (item.Token.Drive == "OneDrive")
                {
                    appToken = await WebAuthorization.RedeemAuthorizationCodeAsync(Client.OneDriveClientID, UriCollection.OneDriveinstalledAppRedirectUri, Client.OneDriveClientSecret,
                                                                                   item.Token.refresh_token, UriCollection.OneDriveTokenUri, "refresh_token", WebAuthorization.TokenOption.REFRESHTOKEN);

                    appToken.refresh_token = item.Token.refresh_token;
                    appToken.Drive         = item.Token.Drive;
                }
                else if (item.Token.Drive == "DropBox")
                {
                    appToken = item.Token;
                }
                if (appToken != null)
                {
                    this.apptoken.Add(appToken);
                    Authentication.UserNameToken unametoken = new Authentication.UserNameToken();
                    DriveInfo driveinfo = null;
                    if (appToken.Drive == "Google")
                    {
                        var result = await HttpHelper.RequstHttp("GET", "https://www.googleapis.com/drive/v2/about", null, appToken.access_token);

                        Dictionary <string, object> drivetext = HttpHelper.DerealizeJson(result.GetResponseStream());
                        var map = new ApiDataMapping();
                        map.Add("name", "DisplayName");
                        map.Add("quotaBytesTotal", "TotalSize", typeof(long));
                        map.Add("quotaBytesUsed", "UseSize", typeof(long));
                        map.Add("quotaBytesUsedAggregate", "EmptySize", typeof(long));
                        map.Add("quotaBytesUsedInTrash", "DeleteSize", typeof(long));
                        map.Add("quotaType", "DriveType");
                        map.Add("rootFolderId", "DriveID");
                        Dictionary <string, object> di = (Dictionary <string, object>)drivetext["user"];
                        driveinfo        = new DriveInfo(drivetext, map);
                        driveinfo.UserID = di["emailAddress"].ToString();
                        driveinfo.Status = "normal";
                        driveinfo.token  = appToken;
                    }
                    else if (appToken.Drive == "OneDrive")
                    {
                        var result = await HttpHelper.RequstHttp("GET", "https://api.onedrive.com/v1.0/drive", null, appToken.access_token);

                        Dictionary <string, object> drivetext = HttpHelper.DerealizeJson(result.GetResponseStream());
                        Dictionary <string, object> owner     = (Dictionary <string, object>)drivetext["owner"];
                        Dictionary <string, object> user      = (Dictionary <string, object>)owner["user"];
                        Dictionary <string, object> quoat     = (Dictionary <string, object>)drivetext["quota"];
                        var map = new ApiDataMapping();
                        map.Add("id", "DriveID", typeof(string));
                        map.Add("driveType", "DriveType");
                        driveinfo             = new DriveInfo(drivetext, map);
                        driveinfo.DisplayName = user["displayName"].ToString();
                        driveinfo.UserID      = user["id"].ToString();
                        driveinfo.TotalSize   = long.Parse(quoat["total"].ToString());
                        driveinfo.EmptySize   = long.Parse(quoat["remaining"].ToString());
                        driveinfo.UseSize     = long.Parse(quoat["used"].ToString());
                        driveinfo.DeleteSize  = long.Parse(quoat["deleted"].ToString());
                        driveinfo.Status      = quoat["state"].ToString();
                        driveinfo.token       = appToken;
                    }
                    else if (appToken.Drive == "DropBox")
                    {
                        var result = await HttpHelper.RequstHttp("GET", "https://api.dropbox.com/1/account/info", null, appToken.access_token);

                        Dictionary <string, object> drivetext = HttpHelper.DerealizeJson(result.GetResponseStream());
                        Dictionary <string, object> quato     = (Dictionary <string, object>)drivetext["quota_info"];
                        var map = new ApiDataMapping();
                        map.Add("uid", "UserId", typeof(string));
                        map.Add("display_name", "DisplayName");
                        driveinfo           = new DriveInfo(drivetext, map);
                        driveinfo.TotalSize = long.Parse(quato["quota"].ToString());
                        driveinfo.UseSize   = long.Parse(quato["normal"].ToString());
                        driveinfo.EmptySize = driveinfo.TotalSize - driveinfo.UseSize;
                        driveinfo.token     = appToken;
                        driveinfo.Status    = "normal";
                    }
                    appToken.uid        = driveinfo.UserID;
                    unametoken.UserName = item.UserName;
                    unametoken.Token    = appToken;
                    drive.Add(driveinfo);
                    await Authentication.SaveToken(new FileDataStore(path), item.UserName, unametoken, CancellationToken.None);
                }
            }
            this.oncomplet(this);
            this.Stop();
        }
Exemple #24
0
        private string BuildBody(string title, string message, string email, bool issue, bool suggestion)
        {
            var sb = new StringBuilder();

            sb.Append("<html xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\">");
            sb.Append("<head><meta content=\"en-us\" http-equiv=\"Content-Language\" />" +
                      "<meta content=\"text/html; charset=utf-16\" http-equiv=\"Content-Type\" />" +
                      "<title>ScreenToGif - Feedback</title>" +
                      "</head>");

            sb.AppendFormat("<style>{0}</style>", Util.Other.GetTextResource("ScreenToGif.Resources.Style.css"));

            sb.Append("<body>");
            sb.AppendFormat("<h1>{0}</h1>", (title ?? "").Length > 0 ? title : "Title of the feedback");
            sb.Append("<div id=\"content\"><div>");
            sb.Append("<h2>Overview</h2>");
            sb.Append("<div id=\"overview\"><table>");

            //First overview row.
            sb.Append("<tr><th>User</th>");
            sb.Append("<th>Machine</th>");
            sb.Append("<th>Startup</th>");
            sb.Append("<th>Date</th>");
            sb.Append("<th>Running</th>");
            sb.Append("<th>Version</th></tr>");

            var culture = new CultureInfo("pt-BR");

            sb.AppendFormat("<tr><td class=\"textcentered\">{0}</td>", Environment.UserName);
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Environment.MachineName);
            sb.AppendFormat(culture, "<td class=\"textcentered\">{0:g}</td>", Global.StartupDateTime);
            sb.AppendFormat(culture, "<td class=\"textcentered\">{0:g}</td>", DateTime.Now);
            sb.AppendFormat(culture, "<td class=\"textcentered\">{0:d':'hh':'mm':'ss}</td>", Global.StartupDateTime != DateTime.MinValue ? DateTime.Now - Global.StartupDateTime : TimeSpan.Zero);
            sb.AppendFormat("<td class=\"textcentered\">{0}</td></tr>", Assembly.GetExecutingAssembly().GetName().Version.ToString(4));

            //Second overview row.
            sb.Append("<tr><th colspan=\"2\">Windows</th>");
            sb.Append("<th>Architecture</th>");
            sb.Append("<th>Used</th>");
            sb.Append("<th>Available</th>");
            sb.Append("<th>Total</th></tr>");

            var status = new Native.MemoryStatusEx(true);

            Native.GlobalMemoryStatusEx(ref status);

            sb.AppendFormat("<td class=\"textcentered\" colspan=\"2\">{0}</td>", Environment.OSVersion.Version);
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Environment.Is64BitOperatingSystem ? "64 bits" : "32 Bits");
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Humanizer.BytesToString(Environment.WorkingSet));
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Humanizer.BytesToString(status.AvailablePhysicalMemory));
            sb.AppendFormat("<td class=\"textcentered\">{0}</td></tr>", Humanizer.BytesToString(status.TotalPhysicalMemory));

            //Third overview row.
            sb.Append("<tr><th colspan=\"3\">E-mail</th>");
            sb.Append("<th>.Net Version</th>");
            sb.Append("<th>Issue?</th>");
            sb.Append("<th>Suggestion?</th></tr>");

            sb.AppendFormat("<td colspan=\"3\" class=\"textcentered\">{0}</td>", (email ?? "").Length > 0 ? email : "*****@*****.**");
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", FrameworkHelper.QueryFrameworkVersion());
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", issue ? "Yes" : "No");
            sb.AppendFormat("<td class=\"textcentered\">{0}</td></tr></table></div></div>", suggestion ? "Yes" : "No");

            //Monitors.
            sb.Append("<br><h2>Monitors</h2><table>");
            sb.Append("<tr><th>Bounds</th>");
            sb.Append("<th>Working Area</th>");
            sb.Append("<th>DPI/Scale</th>");
            sb.Append("<th>Primary?</th></tr>");

            foreach (var monitor in Monitor.AllMonitors)
            {
                sb.AppendFormat("<td class=\"textcentered\">{0}:{1} • {2}x{3}</td>", monitor.Bounds.Left, monitor.Bounds.Top, monitor.Bounds.Width, monitor.Bounds.Height);
                sb.AppendFormat("<td class=\"textcentered\">{0}:{1} • {2}x{3}</td>", monitor.WorkingArea.Left, monitor.WorkingArea.Top, monitor.WorkingArea.Width, monitor.WorkingArea.Height);
                sb.AppendFormat("<td class=\"textcentered\">{0}dpi / {1:#00}%</td>", monitor.Dpi, monitor.Dpi / 96d * 100d);
                sb.AppendFormat("<td class=\"textcentered\">{0}</td></tr>", monitor.IsPrimary ? "Yes" : "No");
            }

            sb.Append("<table>");

            //TODO: Show drawing of monitors, with the position of each window.
            //sb.Append("<svg>" +
            //          "<circle cx=\"40\" cy=\"40\" r=\"24\" style=\"stroke:#006600; fill:#00cc00\"/>" +
            //          "<rect id=\"box\" x=\"0\" y=\"0\" width=\"50\" height=\"50\" style=\"stroke:#006600; fill:#00cc00\"/>" +
            //          "</svg>");

            //Drives.
            sb.Append("<br><h2>Drives</h2><table>");
            sb.Append("<tr><th>Root</th>");
            sb.Append("<th>Used</th>");
            sb.Append("<th>Free</th>");
            sb.Append("<th>Total</th>");
            sb.Append("<th>Format</th>");
            sb.Append("<th>Type</th>");
            sb.Append("<th>Ready?</th></tr>");

            foreach (var drive in DriveInfo.GetDrives())
            {
                #region Try get the size

                var total     = 0L;
                var available = 0L;
                var format    = "";

                try
                {
                    total     = drive.TotalSize;
                    available = drive.AvailableFreeSpace;
                    format    = drive.DriveFormat;
                }
                catch (Exception e)
                {
                    //LogWriter.Log(e, "Not possible to get driver details");
                }

                #endregion

                var used     = total - available;
                var usedPerc = Math.Round(Util.Other.CrossMultiplication(total, used, null), 1);
                var avaiPerc = Math.Round(Util.Other.CrossMultiplication(total, available, null), 1);

                sb.AppendFormat("<td class=\"textcentered\">{0}</td>", drive.Name);
                sb.AppendFormat("<td class=\"textRight\">({0} %) {1}</td>", usedPerc, Humanizer.BytesToString(used, "N1"));
                sb.AppendFormat("<td class=\"textRight\">({0} %) {1}</td>", avaiPerc, Humanizer.BytesToString(available, "N1"));
                sb.AppendFormat("<td class=\"textRight\">{0}</td>", Humanizer.BytesToString(total, "N1"));
                sb.AppendFormat("<td class=\"textcentered\">{0}</td>", format);
                sb.AppendFormat("<td class=\"textcentered\">{0}</td>", drive.DriveType);
                sb.AppendFormat("<td class=\"textcentered\">{0}</td></tr>", drive.IsReady ? "Yes" : "No");
            }

            sb.Append("<table>");

            //Details.
            sb.Append("<br><h2>Details</h2><div><div><table>");
            sb.Append("<tr id=\"ProjectNameHeaderRow\"><th class=\"messageHeader\">Message</th></tr>");
            sb.Append("<tr name=\"MessageRowClassProjectName\">");
            sb.AppendFormat("<td class=\"messageCell\">{0}</td></tr></table>", message.Replace(Environment.NewLine, "<br>"));
            sb.Append("</div></div></div></body></html>");

            return(sb.ToString());
        }
Exemple #25
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            /////ЗАПИСЬ НА КОМПАКТ ДИСК
            if (Disk.IsChecked == true)
            {
                string trialdirectory = path + "TRIALDIRS\\" + RandomString(10);
                if (!Directory.Exists(trialdirectory))
                {
                    Directory.CreateDirectory(trialdirectory);
                }
                if (!Directory.Exists(trialdirectory + "\\pisateli"))
                {
                    Directory.CreateDirectory(trialdirectory + "\\pisateli");
                }
                string path_trial = PreparationCopy(trialdirectory);
                RemoveDataBase(path_trial + "\\pisateli.db");
                string progr          = path + "BurnAware\\DataDisc.exe",
                       arg            = "udf " + trialdirectory;
                DriveInfo[] allDrives = DriveInfo.GetDrives();
                foreach (DriveInfo d in allDrives)
                {
                    if (d.IsReady == true)
                    {
                        if (d.DriveType == DriveType.CDRom)
                        {
                            arg = arg + " " + (d.Name).Substring(0, 1) + " -b";
                        }
                    }
                }
                if (File.Exists(progr))
                {
                    Process.Start(progr, arg);
                }
                else
                {
                    MessageBox.Show("NOFILE");
                }
            }
            if (Flash.IsChecked == true)
            {
                ProgressManager pm = new ProgressManager();

                string path_nositel = ""; ////Путь КУДА БУДЕТ ЗАПИСАНА ПРОГРАММА
                System.Windows.Forms.FolderBrowserDialog fbd      = new System.Windows.Forms.FolderBrowserDialog();
                System.Windows.Forms.DialogResult        d_result = fbd.ShowDialog();
                if (d_result == System.Windows.Forms.DialogResult.OK)
                {
                    path_nositel = fbd.SelectedPath;
                }
                if (path_nositel != "")
                {
                    string trialdirectory = path + "TRIALDIRS\\" + RandomString(10);
                    if (!Directory.Exists(trialdirectory))
                    {
                        Directory.CreateDirectory(trialdirectory);
                    }
                    if (!Directory.Exists(trialdirectory + "\\pisateli"))
                    {
                        Directory.CreateDirectory(trialdirectory + "\\pisateli");
                    }
                    string path_trial = PreparationCopy(trialdirectory);
                    RemoveDataBase(path_trial + "\\pisateli.db");
                    FolderCopy(path_trial, path_nositel, true);
                    FolderDelete(path_trial);
                }
            }
        }
Exemple #26
0
        public void SetSelectedPath(String desiredPath)
        {
            if (String.IsNullOrWhiteSpace(desiredPath))
            {
                return;
            }
            string[] split = Path.GetFullPath(desiredPath).Split(
                new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            string       driveName = new DriveInfo(split[0]).Name.ToLower();
            TreeViewItem curItem   = null;

            foreach (TreeViewItem driveItem in Items)
            {
                DriveInfo info = (DriveInfo)driveItem.Tag;
                if (driveName == info.Name.ToLower())
                {
                    curItem = driveItem;
                    break;
                }
            }
            if (curItem == null)
            {
                return;
            }
            if (!curItem.IsExpanded)
            {
                curItem.IsExpanded = true;
            }
            int index = 1;

            while (index < split.Length)
            {
                string       name     = split[index++].ToLower();
                TreeViewItem nextItem = null;
                foreach (TreeViewItem item in curItem.Items)
                {
                    FileSystemInfo info = (FileSystemInfo)item.Tag;
                    if (info.Name.ToLower().Equals(name))
                    {
                        nextItem = item;
                        break;
                    }
                }
                if (nextItem == null)
                {
                    break;
                }
                if (index == split.Length)
                {
                    nextItem.IsSelected = true;
                    break;
                }
                if (!(nextItem.Tag is DirectoryInfo))
                {
                    break;
                }
                if (!nextItem.IsExpanded)
                {
                    nextItem.IsExpanded = true;
                }
                curItem = nextItem;
            }
        }
Exemple #27
0
        //dir명령어 출력
        public void ShowDirectoryList(string inputPath)
        {
            if (Directory.Exists(inputPath))
            {
                string result;
                string directoryFormat = "{0, -27} {1, -14} {2,-30}";
                string fileFormat      = "{0, -27} {1, 14} {2, -30}";
                int    directoryCount  = 0;
                int    fileCount       = 0;
                long   fileTotalSize   = 0;
                string avaliableFreeSpace;
                string volumeSeriralNumber;

                DirectoryInfo directoryInfo = new DirectoryInfo(inputPath); //디렉토리
                DriveInfo     driveInfo     = new DriveInfo(inputPath.Remove(1));

                avaliableFreeSpace = string.Format("{0:###,###,###,###}", driveInfo.AvailableFreeSpace);

                ManagementObject manageobject = new ManagementObject("win32_logicaldisk.deviceid=\"" + "C" + ":\"");
                manageobject.Get();
                volumeSeriralNumber = manageobject["VolumeSerialNumber"].ToString().Insert(4, "-");

                Console.WriteLine(" {0} 드라이브의 불륨에는 이름이 없습니다.", inputPath.Remove(1));
                Console.WriteLine(" 불륨 일련 번호: " + volumeSeriralNumber + "\n");
                Console.WriteLine(" {0} 디렉터리\n", inputPath);

                if (!inputPath.Equals("C:\\"))
                {
                    Console.WriteLine(string.Format(directoryFormat, directoryInfo.LastWriteTime.ToString("yyyy .MM. dd.  tt hh:mm"),
                                                    "<DIR>", "."));
                    Console.WriteLine(string.Format(directoryFormat, directoryInfo.LastWriteTime.ToString("yyyy .MM. dd.  tt hh:mm"),
                                                    "<DIR>", ".."));
                    directoryCount = 2;
                }

                foreach (var item in directoryInfo.GetFileSystemInfos())
                {
                    if (item.Attributes.HasFlag(FileAttributes.Directory))
                    {
                        if (item.Attributes.ToString().Equals("Directory") || item.Attributes.ToString().Equals("ReadOnly, Directory") ||
                            item.Attributes.ToString().Equals("Directory, NotContentIndexed") || item.Attributes.ToString().Equals("Directory, Compressed, NotContentIndexed"))
                        {
                            directoryCount = directoryCount + 1;
                            result         = string.Format(directoryFormat, item.LastWriteTime.ToString("yyyy .MM. dd.  tt hh:mm"), "<DIR>", item.Name);
                            Console.WriteLine(result);
                        }
                    }

                    if (item.Attributes.HasFlag(FileAttributes.Archive))
                    {
                        if (!item.Attributes.HasFlag(FileAttributes.Hidden) && !item.Attributes.HasFlag(FileAttributes.System))
                        {
                            long fileSize = new FileInfo(inputPath + "\\" + item.Name).Length;
                            fileCount     = fileCount + 1;
                            fileTotalSize = fileTotalSize + fileSize;
                            result        = string.Format(fileFormat, item.LastWriteTime.ToString("yyyy. MM. dd.  tt hh:mm"), string.Format("{0:###,###,###,###}", fileSize), item.Name);
                            Console.WriteLine(result);
                        }
                    }
                }

                Console.WriteLine(string.Format("{0, 22} {1, 18}", fileCount + "개 파일", string.Format("{0:###,###,###,###}", fileTotalSize)) + " 바이트");
                Console.WriteLine(string.Format("{0, 24} {1, 15}", directoryCount + "개 디렉터리", avaliableFreeSpace) + " 바이트 남음");
                Console.WriteLine();
                command.InputCommand(inputPath);
            }
        }
Exemple #28
0
 public RemoveableDriveMedium(DriveInfo driveInfo) : base(driveInfo)
 {
 }
 public void SetVolumeLabel_Throws_PlatformNotSupportedException()
 {
     var root = new DriveInfo("/");
     Assert.Throws<PlatformNotSupportedException>(() => root.VolumeLabel = root.Name);
 }
Exemple #30
0
        private static List <FrnFilePath> GetFolderPath(UsnEntry[] folders, DriveInfo drive)
        {
            Dictionary <UInt64, FrnFilePath> pathDic = new Dictionary <ulong, FrnFilePath>();

            pathDic.Add(ROOT_FILE_REFERENCE_NUMBER,
                        new FrnFilePath(ROOT_FILE_REFERENCE_NUMBER, null, string.Empty, drive.Name.TrimEnd('\\')));

            foreach (var folder in folders)
            {
                pathDic.Add(folder.FileReferenceNumber,
                            new FrnFilePath(folder.FileReferenceNumber, folder.ParentFileReferenceNumber, folder.FileName));
            }

            Stack <UInt64> treeWalkStack = new Stack <ulong>();

            foreach (var key in pathDic.Keys)
            {
                treeWalkStack.Clear();

                FrnFilePath currentValue = pathDic[key];

                if (string.IsNullOrWhiteSpace(currentValue.Path) &&
                    currentValue.ParentFileReferenceNumber.HasValue &&
                    pathDic.ContainsKey(currentValue.ParentFileReferenceNumber.Value))
                {
                    FrnFilePath parentValue = pathDic[currentValue.ParentFileReferenceNumber.Value];

                    while (string.IsNullOrWhiteSpace(parentValue.Path) &&
                           parentValue.ParentFileReferenceNumber.HasValue &&
                           pathDic.ContainsKey(parentValue.ParentFileReferenceNumber.Value))
                    {
                        currentValue = parentValue;

                        if (currentValue.ParentFileReferenceNumber.HasValue &&
                            pathDic.ContainsKey(currentValue.ParentFileReferenceNumber.Value))
                        {
                            treeWalkStack.Push(key);
                            parentValue = pathDic[currentValue.ParentFileReferenceNumber.Value];
                        }
                        else
                        {
                            parentValue = null;
                            break;
                        }
                    }

                    if (parentValue != null)
                    {
                        currentValue.Path = BuildPath(currentValue, parentValue);

                        while (treeWalkStack.Count() > 0)
                        {
                            UInt64 walkedKey = treeWalkStack.Pop();

                            FrnFilePath walkedNode = pathDic[walkedKey];
                            FrnFilePath parentNode = pathDic[walkedNode.ParentFileReferenceNumber.Value];

                            walkedNode.Path = BuildPath(walkedNode, parentNode);
                        }
                    }
                }
            }

            var result = pathDic.Values.Where(p => !string.IsNullOrWhiteSpace(p.Path) && p.Path.StartsWith(drive.Name)).ToList();

            return(result);
        }
Exemple #31
0
 /// <summary>
 /// Adds the logical drives to the ListView or to the TreeView ; e.g. C:\, D:\..
 /// </summary>
 /// <param name="computerNode">If you add to TreeView</param>
 /// <param name="listView">If you add to ListView</param>
 public void AddLogicalDrives(TreeNode computerNode = null, ListView listView = null)
 {
     try
     {
         if (computerNode != null)
         {
             foreach (String drive in Environment.GetLogicalDrives())
             {
                 if (Directory.Exists(drive))
                 {
                     TreeNode driveNode = new TreeNode();
                     driveNode.Tag = drive;
                     driveNode.Text = drive;
                     driveNode.ImageKey = driveItems[1];
                     driveNode.SelectedImageKey = driveItems[1];
                     computerNode.Nodes.Add(driveNode);
                 }
             }
         }
         else
         {
             listView.Items.Clear();
             foreach (String drive in Environment.GetLogicalDrives())
             {
                 if (Directory.Exists(drive))
                 {
                     DriveInfo driveInfo = new DriveInfo(drive);
                     long d = 1073741824;
                     listView.Items.Add(new ListViewItem(new String[] { drive, driveItems[0], String.Empty, drive, (driveInfo.TotalSize / d).ToString() + " GB" }, driveItems[1]));
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        protected override void Refresh(RefreshFiles[] refreshFiles, CancellationToken token)
        {
            CanDisplayProgress = RootItem.Type == FileItemType.Volume ||
                                 (RootItem.Type == FileItemType.Computer &&
                                  !RootItem.Children.Any(f => f.Type != FileItemType.Volume &&
                                                         f.Type != FileItemType.FreeSpace && f.Type != FileItemType.Unknown));
            if (CanDisplayProgress)
            {
                if (RootItem.Type == FileItemType.Volume)
                {
                    try {
                        if (RootItem.CheckExists())
                        {
                            DriveInfo driveInfo = new DriveInfo(RootItem.RootPath);
                            TotalSize      = driveInfo.TotalSize;
                            TotalFreeSpace = driveInfo.TotalFreeSpace;
                        }
                        else
                        {
                            CanDisplayProgress = false;
                        }
                    }
                    catch {
                        CanDisplayProgress = false;
                    }
                }
                else if (RootItem.Type == FileItemType.Computer)
                {
                    bool anySuccess = false;
                    foreach (FileItemBase child in RootItem.Children)
                    {
                        if (child is RootItem root)
                        {
                            try {
                                if (root.CheckExists())
                                {
                                    DriveInfo driveInfo = new DriveInfo(root.RootPath);
                                    TotalSize      += driveInfo.TotalSize;
                                    TotalFreeSpace += driveInfo.TotalFreeSpace;
                                    anySuccess      = true;
                                    continue;
                                }
                            }
                            catch { }
                            TotalSize      += root.CachedTotalSize;
                            TotalFreeSpace += root.CachedFreeSpace;
                        }
                    }
                    if (!anySuccess)
                    {
                        CanDisplayProgress = false;
                    }
                }
            }
            // Reset the progress if applicable
            TotalScannedSize = Extensions.TotalSize - refreshFiles.Sum(rf => rf.Files.Sum(f => f.Size));
            ProgressState    = ScanProgressState.Started;

            foreach (RefreshFiles refresh in refreshFiles)
            {
                FolderItem parent         = refresh.Parent;
                FolderItem fileCollection = parent.GetFileCollection();

                Queue <FolderItem> subdirs = new Queue <FolderItem>();

                foreach (FileItemBase refreshChild in refresh.Files)
                {
                    if (!refreshChild.Refresh())
                    {
                        string fullName = refreshChild.FullName;
                        parent.RemoveItem(refreshChild, ref fileCollection);

                        // See if the type changed (file <-> directory)
                        FileItemBase child = null;
                        if (refreshChild.Type == FileItemType.File)
                        {
                            DirectoryInfo info = new DirectoryInfo(fullName);
                            if (info.Exists)
                            {
                                FolderItem folder = new FolderItem(info);
                                child = folder;
                                // Folder exists enqueue it for scanning
                                if (!info.Attributes.HasFlag(FileAttributes.ReparsePoint))
                                {
                                    subdirs.Enqueue(folder);
                                }
                            }
                        }
                        else if (refreshChild.Type == FileItemType.Directory)
                        {
                            FileInfo info = new FileInfo(fullName);
                            if (info.Exists)
                            {
                                ExtensionItem extension = Extensions.GetOrAddFromPath(fullName);
                                FileItem      file      = new FileItem(info, extension);
                                child = file;
                                // File exists, add it to the scanned size
                                if (!info.Attributes.HasFlag(FileAttributes.ReparsePoint))
                                {
                                    TotalScannedSize += child.Size;
                                }
                            }
                        }
                        if (child != null)
                        {
                            FileItem firstFile = parent.GetFirstFile();
                            parent.AddItem(child, ref fileCollection, ref firstFile);
                        }
                    }
                    else if (!refreshChild.IsReparsePointFile)
                    {
                        // Folder exists enqueue it for scanning
                        if (refreshChild is FolderItem folder)
                        {
                            subdirs.Enqueue(folder);
                        }
                        // File exists, add it to the scanned size
                        else
                        {
                            TotalScannedSize += refreshChild.Size;
                        }
                    }

                    if (AsyncChecks(token))
                    {
                        return;
                    }
                }

                if (subdirs.Count > 0)
                {
                    RefreshFolders(subdirs, token);
                }

                if (AsyncChecks(token))
                {
                    return;
                }
            }
        }
        private void CreateDriveSettings(DriveInfo drive, string password)
        {
            XmlDriveSettings driveSettings = new XmlDriveSettings(drive.Root);
            driveSettings.WriteMd5Password(GetMd5Hash(password));

            byte[] encPassword = encryptor.EnDecrypt(true, Encoding.Default.GetBytes(password));
            password = Encoding.Default.GetString(encPassword);
            driveSettings.WritePassword(password);
        }
Exemple #34
0
        // This will get all the files  and and tries to encrypt it. It works together with "ShowAllFoldersUnder()"
        // to get as many files as possible.
        public void GetFiles(string mode = "encrypt")
        {
            try
            {
                // Encrypt Desktop Files first!
                string[] desktopFiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "*.*", SearchOption.AllDirectories);
                foreach (string s in desktopFiles)
                {
                    try
                    {
                        if (!s.Contains(Properties.Settings.Default.extension) && !s.Contains("Sytem Volume Information") && mode != "decrypt")
                        {
                            // FUSE
                            //Task.Run(() => Crypto.FileEncrypt(s, Properties.Settings.Default.key));
                            write("Encrypted " + s);

                            try
                            {
                                // FUSE
                                //File.Delete(s);
                            }
                            catch (Exception ex2)
                            {
                                write("Cant delete file " + ex2.Message);
                                Log(ex2.Message, "GetFiles > File Delete Error");
                            }
                        }
                        else if (mode == "decrypt")
                        {
                            if (s.Contains(Properties.Settings.Default.extension) && !s.Contains("System Volume Information"))
                            {
                                Task.Run(() => Crypto.FileDecrypt(s, s.Replace(Properties.Settings.Default.extension, ""), Properties.Settings.Default.key));
                                write("Decrypted " + s);

                                try
                                {
                                    // Delete original encrypted file?
                                    //File.Delete(s);
                                }
                                catch (Exception ex2)
                                {
                                    write("Cant delete file " + ex2.Message);
                                    Log(ex2.Message, "GetFiles > File Delete Error");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(ex.Message, "Getfiles > General Error");
                    }
                }

                // Now Encrypt whole hard drive
                foreach (var drive in DriveInfo.GetDrives())
                {
                    // This will try to create message in eighter plain text file or html file.
                    try
                    {
                        if (Properties.Settings.Default.message.Length > 0)
                        {
                            File.WriteAllText(drive.Name + "\\message.html", Properties.Settings.Default.message);
                            File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\message.html", Properties.Settings.Default.message);

                            write("Created File message.html on drive " + drive.Name + "\\message");
                            Log("File 'message.html' created on drive " + drive.Name + "\\message.html", "GetFiles > Check Message Settings");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(ex.Message, "GetFiles > Create Message File");
                        write(ex.Message);
                    }


                    try
                    {
                        write("Found drive " + drive.Name);
                        Log("Found drive " + drive.Name, "GetFiles > Drive State Check");

                        try
                        {
                            //  if the drive is ready try to get all the files and files in subfolders using ShowAllFoldersUnder()
                            if (drive.IsReady)
                            {
                                ShowAllFoldersUnder(drive.Name, 0);
                            }
                            else
                            {
                                Log("Found drive " + drive.Name + " , but it's not ready.", "GetFiles > Drive State Check");
                                write("Found drive " + drive.Name + " , but it's not ready.");
                            }
                        }
                        catch { }
                    }
                    catch (Exception ex1)
                    {
                        write("ex1 " + ex1.Message);
                        Log(ex1.Message, "GetFiles > Drive Error");
                    }
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, "GetFiles > General Drive Error");
            }

            write("Done getting stuff :)");
        }
        public void SendPerformanceHistory()
        {
            HardwareMonitorService service        = new HardwareMonitorService();
            UpdateVisitor          updateVisitor1 = new UpdateVisitor();
            var drives = DriveInfo.GetDrives();
            int i      = 0;

            Computer computer1 = new Computer()
            {
                CPUEnabled           = true,
                FanControllerEnabled = true,
                GPUEnabled           = true,
                HDDEnabled           = true,
                MainboardEnabled     = true,
                RAMEnabled           = true
            };

            bool hasPackageTemp = false;
            var  ramLoad        = new List <double>();
            var  ramString      = "";
            var  cpuTemp        = new List <double>();
            var  cpuLoad        = new List <double>();
            var  cpuTempHistory = new List <object>();
            var  cpuLoadHistory = new List <object>();
            var  diskList       = new List <string>();
            var  cpuList        = new List <string>();

            while (i != -1)
            {
                computer1.Open();
                computer1.Accept(updateVisitor1);

                foreach (DriveInfo drive in drives)
                {
                    if (drive.IsReady)
                    {
                        var diskInfo = drive.Name + "," + drive.VolumeLabel + "," + drive.DriveType + "," + drive.DriveFormat + "," + drive.TotalFreeSpace + "," + drive.TotalSize;
                        diskList.Add(diskInfo);
                    }
                }

                foreach (var t2 in computer1.Hardware)
                {
                    if (t2.HardwareType == HardwareType.CPU)
                    {
                        cpuList.Add(t2.Name);
                        hasPackageTemp = t2.Sensors.Any(x => x.SensorType == SensorType.Temperature && x.Name == "CPU Package");
                        foreach (var t1 in t2.Sensors)
                        {
                            if (t1.SensorType == SensorType.Temperature && ((hasPackageTemp && t1.Name.Contains("Package")) || t1.Name == "CPU Core #1"))
                            {
                                cpuTemp.Add(t1.Value.GetValueOrDefault());
                            }
                            if (t1.SensorType == SensorType.Load && t1.Name == "CPU Total")
                            {
                                cpuLoad.Add(t1.Value.GetValueOrDefault());
                            }
                        }
                    }

                    if (t2.HardwareType != HardwareType.RAM)
                    {
                        continue;
                    }

                    foreach (var t1 in t2.Sensors)
                    {
                        if (t1.SensorType == SensorType.Load)
                        {
                            ramLoad.Add(t1.Value.GetValueOrDefault());
                        }
                        if (t1.SensorType != SensorType.Data || t1.Name != "Used Memory")
                        {
                            continue;
                        }
                        var available = t2.Sensors.FirstOrDefault(x => x.SensorType == SensorType.Data && x.Name == "Available Memory");
                        if (available == null)
                        {
                            continue;
                        }
                        var used = t1.Value.GetValueOrDefault();
                        ramString = Math.Round(used, 0) + "/" + Math.Round(used + available.Value.GetValueOrDefault(), 0) + " GB In Use";
                    }
                }

                service.SaveHardwareData(cpuList, ramString, cpuLoad, ramLoad.FirstOrDefault(), cpuTemp);
                computer1.Close();
                i++;

                cpuLoadHistory = service.GetCPULoadHistory();
                ramLoad        = service.GetRAMHistory();
                cpuTempHistory = service.GetCPUTempHistory();

                Clients.All.updatePerformanceHistory(cpuList, cpuLoadHistory, ramLoad, cpuTempHistory, ramString);

                cpuLoadHistory.Clear();
                cpuTempHistory.Clear();
                cpuTemp.Clear();
                cpuLoad.Clear();
                diskList.Clear();
                cpuList.Clear();
                ramLoad.Clear();

                Thread.Sleep(1000);
            }
        }
Exemple #36
0
        public void HandleCommunication()
        {
            _sReader = new StreamReader(_client.GetStream(), Encoding.ASCII);
            _sWriter = new StreamWriter(_client.GetStream(), Encoding.ASCII);

            _isConnected = true;
            String sData = null;

            while (_client.Connected)
            {
                //Console.Write("&gt; ");
                //sData = Console.ReadLine();

                // write data and make sure to flush, or the buffer will continue to
                // grow, and your data might not be sent when you want it, and will
                // only be sent once the buffer is filled.
                //_sWriter.WriteLine(sData);
                //_sWriter.Flush();

                // if you want to receive anything
                String sDataIncomming = null;
                try
                {
                    sDataIncomming = _sReader.ReadLine();
                    dataTab        = new string[1];
                    dataTab        = sDataIncomming.Split('_');
                    if (dataTab[1] == "1")
                    {
                        MessageBox.Show(dataTab[0], "server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    if (dataTab[1] == "2")
                    {
                        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
                        synthesizer.Volume = 70;
                        synthesizer.SpeakAsync(dataTab[0]);
                    }
                    if (dataTab[1] == "5")
                    {
                        if (dataTab[0] == "true")
                        {
                            BlockInput(true);
                        }
                        else
                        {
                            BlockInput(false);
                        }
                    }
                    if (dataTab[1] == "7")
                    {
                        Process.Start("shutdown.exe", "-s -t 0");
                    }
                    if (dataTab[1] == "8")
                    {
                        Process.Start("shutdown.exe", "-r -t 0");
                    }
                    if (dataTab[1] == "9")
                    {
                        Process.Start("shutdown.exe", "-l -t 0");
                    }
                    if (dataTab[1] == "10")
                    {
                        int hwnd = FindWindow("Shell_TrayWnd", "");
                        ShowWindow(hwnd, SW_HIDE);
                    }
                    if (dataTab[1] == "11")
                    {
                        int hwnd = FindWindow("Shell_TrayWnd", "");
                        ShowWindow(hwnd, SW_SHOW);
                    }
                    if (dataTab[1] == "12")
                    {
                        rd = true;
                        Thread tRD = new Thread(startRD);
                        tRD.Start();
                    }
                    if (dataTab[1] == "13")
                    {
                        rd = false;
                    }
                    if (dataTab[1] == "14")
                    {
                        wc = true;
                        Thread WC = new Thread(() => startWebCam(dataTab[0]));
                        WC.Start();
                    }
                    if (dataTab[1] == "15")
                    {
                        wc = false;
                        stopWebcam();
                    }
                    if (dataTab[1] == "16")
                    {
                        string webcamNames = null;
                        VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                        foreach (FilterInfo VideoCaptureDevice in VideoCaptureDevices)
                        {
                            webcamNames += VideoCaptureDevice.Name + "_";
                        }
                        _sWriter.WriteLine(webcamNames);
                        _sWriter.Flush();
                    }
                    if (dataTab[1] == "17")
                    {
                        Process p = Process.Start("notepad.exe");
                        p.WaitForInputIdle();
                        IntPtr h = p.MainWindowHandle;
                        SetForegroundWindow(h);
                        try
                        {
                            for (int i = 0; i < dataTab[0].Length; i++)
                            {
                                SendKeys.SendWait(dataTab[0][i].ToString());
                                Thread.Sleep(50);
                            }
                        }
                        catch
                        {
                            SendKeys.SendWait("Hello men, i see you");
                        }
                    }
                    if (dataTab[1] == "18")
                    {
                        try
                        {
                            foreach (DriveInfo drive in DriveInfo.GetDrives())
                            {
                                if (drive.DriveType == DriveType.CDRom)
                                {
                                    cd.openDrive(drive.RootDirectory.ToString());
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    if (dataTab[1] == "19")
                    {
                        try
                        {
                            foreach (DriveInfo drive in DriveInfo.GetDrives())
                            {
                                if (drive.DriveType == DriveType.CDRom)
                                {
                                    cd.closeDrive(drive.RootDirectory.ToString());
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    //if (dataTab[1] == "20")
                    //{
                    MouseClick(false);
                    //}
                    if (dataTab[1] == "21")
                    {
                        MouseClick(true);
                    }
                }
                catch
                {
                    //Application.Restart();
                }
            }
        }
        static void Main(string[] args)
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo d in allDrives)
            {
                Console.WriteLine("Drive Name" + d.Name);
                Console.WriteLine("  Drive type " + d.DriveType);
                if (d.IsReady == true)
                {
                    Console.WriteLine("Available space ", d.AvailableFreeSpace);
                    Console.WriteLine("Total size in bytes ", d.TotalSize);
                }
            }

            DirectoryInfo directoryInfo = new DirectoryInfo("C:\\UCN Code Base\\Programming-in-C-Exam-70-483-MCSD-Guide\\Book70483Samples");

            foreach (DirectoryInfo f in directoryInfo.GetDirectories())
            {
                Console.WriteLine("Directory Name is " + f.Name);
                Console.WriteLine("Directory created time is " + f.CreationTime);
                Console.WriteLine("Directory last modified time is " + f.LastAccessTime);
            }

            DirectoryInfo directoryInfoExists = new DirectoryInfo("C:\\UCN Code Base\\Programming-in-C-Exam-70-483-MCSD-Guide\\Book70483Samples\\Chapter 20");

            if (directoryInfoExists.Exists)
            {
                Console.WriteLine("It exists");
            }
            else
            {
                Directory.CreateDirectory("C:\\UCN Code Base\\Programming-in-C-Exam-70-483-MCSD-Guide\\Book70483Samples\\Chapter 20");
            }

            DirectoryInfo chapter20 = new DirectoryInfo("C:\\UCN Code Base\\Programming-in-C-Exam-70-483-MCSD-Guide\\Book70483Samples\\Chapter 20");


            foreach (FileInfo f in chapter20.GetFiles())
            {
                Console.WriteLine("File Name is " + f.FullName);
                Console.WriteLine("File created time is " + f.CreationTime);
                Console.WriteLine("File last modified time is " + f.LastAccessTime);
            }

            string file = "C:\\UCN Code Base\\Programming-in-C-Exam-70-483-MCSD-Guide\\Book70483Samples\\Chapter 20\\IO Operations.txt";

            if (File.Exists(file))
            {
                Console.WriteLine("File Existis in the mentioned path");
            }
            else
            {
                Console.WriteLine("File does not exists in the mentioned path");
            }

            string sourceFileLocation = @"C:\UCN Code Base\Programming-in-C-Exam-70-483-MCSD-Guide\Book70483Samples\Chapter 20";
            string fileName           = @"IO Operations.txt";
            string properFilePath     = Path.Combine(sourceFileLocation, fileName);

            Console.WriteLine(Path.GetDirectoryName(properFilePath));
            Console.WriteLine(Path.GetExtension(properFilePath));
            Console.WriteLine(Path.GetFileName(properFilePath));
            Console.WriteLine(Path.GetPathRoot(properFilePath));
            Console.ReadLine();

            /*string sourceFileLocation = "C:\\UCN Code Base\\Programming-in-C-Exam-70-483-MCSD-Guide\\Book70483Samples\\Chapter 20\\IO Operations.txt";
             * string targetFileLocation = "C:\\UCN Code Base\\Programming-in-C-Exam-70-483-MCSD-Guide\\Book70483Samples\\Chapter 21\\New File.txt";
             *
             * if (File.Exists(sourceFileLocation))
             * {
             *  File.Move(sourceFileLocation, targetFileLocation);
             * }
             * else
             * {
             *  Console.WriteLine("File does not exists in the mentioned path");
             * }
             *
             * Console.ReadLine();
             *
             *
             * if (File.Exists(targetFileLocation))
             * {
             *  File.Copy(targetFileLocation, sourceFileLocation);
             * }
             * else
             * {
             *  Console.WriteLine("File does not exists in the mentioned path");
             * }
             *
             * File.Delete(sourceFileLocation);
             */
        }
Exemple #38
0
 public Drive(InternalDriveType?driveType, DriveInfo driveInfo)
 {
     this.InternalDriveType = driveType;
     this.DriveInfo         = driveInfo;
 }
 public bool RemoveDrive(DriveInfo drive)
 {
     foreach (XmlNode table in xmlDoc.DocumentElement.ChildNodes)
     {
         string root = string.Empty;
         foreach (XmlNode ch in table.ChildNodes)
         {
             if (ch.Name == rootElem)
             {
                 root = ch.InnerText;
                 break;
             }
         }
         if (drive.Root == root)
         {
             xmlDoc.DocumentElement.RemoveChild(table);
             xmlDoc.Save(settingsFile);
             return true;
         }
     }
     return false;
 }
Exemple #40
0
        public bool enoughSpaceInDisk(string path, string filename)
        {
            bool result = true;

            string        filepath       = path + filename;
            XmlReader     reader         = XmlReader.Create(@filepath);
            StringBuilder XmlDeclaration = new StringBuilder();
            string        drive          = Path.GetPathRoot(path);
            DriveInfo     driveInfo      = new DriveInfo(drive);
            long          driveSpace     = driveInfo.TotalFreeSpace;
            long          requiredSpace  = 0;
            int           numOfTabs      = 1;
            bool          writer         = false;

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                case XmlNodeType.Whitespace:
                    if (writer)
                    {
                        requiredSpace += "\r\n".Length;
                    }
                    break;

                case XmlNodeType.XmlDeclaration:

                    XmlDeclaration.Append("<?" + reader.Name);
                    if (reader.HasAttributes)
                    {
                        reader.MoveToFirstAttribute();
                        for (int i = 0; i < reader.AttributeCount; i++)
                        {
                            XmlDeclaration.Append(" " + reader.Name + "=\"" + reader.GetAttribute(i) + "\"");
                            reader.MoveToNextAttribute();
                        }
                        XmlDeclaration.Append("?>");
                    }
                    break;

                case XmlNodeType.Element:
                    if (reader.Name == "Product")
                    {
                        requiredSpace += XmlDeclaration.ToString().Length;
                        requiredSpace += "<line>".Length;
                        writer         = true;
                    }
                    if (writer)
                    {
                        bool isEmptyElement = reader.IsEmptyElement;
                        for (int j = 0; j < numOfTabs; ++j)
                        {
                            requiredSpace += "\t".Length;
                        }
                        if (!isEmptyElement)
                        {
                            ++numOfTabs;
                        }
                        requiredSpace += ("<" + reader.Name).Length;
                        if (reader.HasAttributes)
                        {
                            reader.MoveToFirstAttribute();
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                requiredSpace += (" " + reader.Name + "=\"" + reader.GetAttribute(i) + "\"").Length;
                                reader.MoveToNextAttribute();
                            }
                        }
                        if (isEmptyElement)
                        {
                            requiredSpace += "/>\r\n".Length;
                        }
                        else
                        {
                            requiredSpace += ">\r\n".Length;
                        }
                    }
                    break;

                case XmlNodeType.EndElement:
                    if (writer)
                    {
                        --numOfTabs;
                        for (int j = 0; j < numOfTabs; ++j)
                        {
                            requiredSpace += "\t".Length;
                        }
                        requiredSpace += ("</" + reader.Name + ">").Length;
                    }
                    if (reader.Name == "Product")
                    {
                        requiredSpace += "</line>".Length;
                        writer         = false;
                    }
                    break;

                case XmlNodeType.Text:
                    if (writer)
                    {
                        requiredSpace += (reader.Value).Length;
                    }

                    break;
                }
            }

            return(requiredSpace <= driveSpace);
        }
Exemple #41
0
 public static IEnumerable <DriveInfo> GetAllDrives()
 {
     return(DriveInfo.GetDrives());
 }
 public GetSystemDrives()
 {
     driveInfo = DriveInfo.GetDrives();
 }
Exemple #43
0
 // Initializes a new object of this class.
 public CacheConnector(DriveInfo drive)
     : base(drive)
 {
 }
Exemple #44
0
        public static AbstractHarddrive CreateInstance(ISmart smart,
                                                       int driveIndex, ISettings settings)
        {
            IntPtr deviceHandle = smart.OpenDrive(driveIndex);

            string name             = null;
            string firmwareRevision = null;

            DriveAttributeValue[] values = { };

            if (deviceHandle != smart.InvalidHandle)
            {
                bool nameValid = smart.ReadNameAndFirmwareRevision(deviceHandle,
                                                                   driveIndex, out name, out firmwareRevision);
                bool smartEnabled = smart.EnableSmart(deviceHandle, driveIndex);

                if (smartEnabled)
                {
                    values = smart.ReadSmartData(deviceHandle, driveIndex);
                }

                smart.CloseHandle(deviceHandle);

                if (!nameValid)
                {
                    name             = null;
                    firmwareRevision = null;
                }
            }
            else
            {
                string[] logicalDrives = smart.GetLogicalDrives(driveIndex);
                if (logicalDrives == null || logicalDrives.Length == 0)
                {
                    return(null);
                }

                bool hasNonZeroSizeDrive = false;
                foreach (string logicalDrive in logicalDrives)
                {
                    try {
                        DriveInfo di = new DriveInfo(logicalDrive);
                        if (di.TotalSize > 0)
                        {
                            hasNonZeroSizeDrive = true;
                            break;
                        }
                    } catch (ArgumentException) {
                    } catch (IOException) {
                    } catch (UnauthorizedAccessException) {
                    }
                }

                if (!hasNonZeroSizeDrive)
                {
                    return(null);
                }
            }

            if (string.IsNullOrEmpty(name))
            {
                name = "Generic Hard Disk";
            }

            if (string.IsNullOrEmpty(firmwareRevision))
            {
                firmwareRevision = "Unknown";
            }

            foreach (Type type in hddTypes)
            {
                // get the array of name prefixes for the current type
                NamePrefixAttribute[] namePrefixes = type.GetCustomAttributes(
                    typeof(NamePrefixAttribute), true) as NamePrefixAttribute[];

                // get the array of the required SMART attributes for the current type
                RequireSmartAttribute[] requiredAttributes = type.GetCustomAttributes(
                    typeof(RequireSmartAttribute), true) as RequireSmartAttribute[];

                // check if all required attributes are present
                bool allRequiredAttributesFound = true;
                foreach (var requireAttribute in requiredAttributes)
                {
                    bool adttributeFound = false;
                    foreach (DriveAttributeValue value in values)
                    {
                        if (value.Identifier == requireAttribute.AttributeId)
                        {
                            adttributeFound = true;
                            break;
                        }
                    }
                    if (!adttributeFound)
                    {
                        allRequiredAttributesFound = false;
                        break;
                    }
                }

                // if an attribute is missing, then try the next type
                if (!allRequiredAttributesFound)
                {
                    continue;
                }

                // check if there is a matching name prefix for this type
                foreach (NamePrefixAttribute prefix in namePrefixes)
                {
                    if (name.StartsWith(prefix.Prefix, StringComparison.InvariantCulture))
                    {
                        return(Activator.CreateInstance(type, smart, name, firmwareRevision,
                                                        driveIndex, settings) as AbstractHarddrive);
                    }
                }
            }

            // no matching type has been found
            return(null);
        }
Exemple #45
0
 public DataDiscMedium(DriveInfo driveInfo) : base(driveInfo)
 {
 }
        private bool ValidPassword(DriveInfo drive)
        {
            string password = GetDrivePassword(drive);
            XmlDriveSettings dSettings = new XmlDriveSettings(drive.Root);
            string md5Password = dSettings.ReadMd5Password();

            if (VerifyMd5Hash(password, md5Password))
            {
                return true;
            }

            return false;
        }
Exemple #47
0
    protected void setServerInfo()
    {
        StringBuilder s = new StringBuilder();
        space(s);
        row(s, "Disk usage", Utils.GetByteSizeString(WAFRuntime.Engine.GetGlobalValue<long>("TotalFileByteSize")));
        row(s, "File count", WAFRuntime.Engine.GetGlobalValue<int>("TotalFileCount"));
        try {
            string path1 = Path.GetPathRoot(Request.PhysicalPath).ToUpper();
            DriveInfo di = new DriveInfo(path1);
            row(s, "Free data disk", Utils.GetByteSizeString(di.AvailableFreeSpace));
            string path2 = Path.GetPathRoot(Path.GetPathRoot("C:\\"));
            if (path2 != path1) {
                DriveInfo diSystem = new DriveInfo(path2);
                row(s, "Free system disk", Utils.GetByteSizeString(diSystem.AvailableFreeSpace));
            } else {
                row(s, "Free system disk", "(Same disk)");
            }
        } catch { }

        try {
            row(s, "IIS App Pool mem", Utils.GetByteSizeString(System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64));
        } catch { }
        row(s, "Managed memory", Utils.GetByteSizeString(GC.GetTotalMemory(false)));

        title(s, "Application restarts last 12 hour");
        s.Append("<div style=\"background-position: center top; background-image:url(Charts/Server.ashx?Data=CPU&height=120&width=290); height:78px; width:100%\"  ></div>");
        title(s, "App Pool Memory usage last 30 minutes");
        s.Append("<div style=\"background-position: center top; background-image:url(Charts/Server.ashx?Data=Memory&height=120&width=290); height:78px; width:100%\"  ></div>");
        litServer.Text = s.ToString();
    }
Exemple #48
0
        static void Main(string[] args)
        {
            string directoryPath = @"/test/second/";
            string fileInput = "input.txt";
            string fileOutput = "output.txt";
            string driveName = "";
            int    firstNumber = 0, secondNumber = 0, sum = 0;
            bool   isPars;

            DriveInfo[] drives = DriveInfo.GetDrives();

            for (int i = 0; i < drives.Length; i++)
            {
                Console.WriteLine($"{i}.{drives[i].Name}");
            }

            Console.WriteLine("Введите номер диска, на который будет записан файл");

            string driveNumberAsString = Console.ReadLine();

            int driveNumber = 0;

            if (!int.TryParse(driveNumberAsString, out driveNumber))
            {
                Console.WriteLine("Ошибка ввода, будет произведена запись на первый указанный диск.");
            }
            driveName = drives[driveNumber].Name;

            if (!Directory.Exists(driveName + directoryPath))
            {
                Directory.CreateDirectory(driveName + directoryPath);
            }
            try
            {
                if (!File.Exists(driveName + directoryPath + fileInput))
                {
                    File.Create(driveName + directoryPath + fileInput);
                }


                using (StreamWriter streamWriter = new StreamWriter(driveName + directoryPath + fileInput))
                {
                    Console.WriteLine("\nВведите 1 число:");
                    isPars = int.TryParse(Console.ReadLine(), out firstNumber);

                    Console.WriteLine("\nВведите 2 число:");
                    isPars = int.TryParse(Console.ReadLine(), out secondNumber);

                    streamWriter.WriteLine(firstNumber + " " + secondNumber);
                    sum = firstNumber + secondNumber;
                    using (StreamWriter streamWriterOutput = new StreamWriter(driveName + directoryPath + fileOutput))
                    {
                        streamWriterOutput.WriteLine(sum);
                    }
                }
                using (StreamReader streamReader = new StreamReader(driveName + directoryPath + fileOutput))
                {
                    Console.WriteLine("\nСумма:" + streamReader.ReadToEnd());
                }
            }

            catch (IOException exception)
            {
                Console.WriteLine(exception.Message);
            }

            Console.WriteLine("Просмотрите файлы input.txt и output.txt");
            Console.ReadKey();
        }
        /// <summary>
        /// Updates tree view selection, so that it corresponds to specified <see cref="SelectedPath"/> value.
        /// </summary>
        /// <param name="value"></param>
        private void SetSelectedPath(String value)
        {
            //For now, there are some issues with correct item (un)selection,
            //cause item that was previously selected, becomes selected again after this code, that selects a new item.
            //It may be related somehow to TreeViewItem.IsSelected behavior.

            //Re-creating items on each SelectedPath = XXX expression (or binding evaluations) 
            //POTENTIALLY may cause lags at some cases (when getting DriveInfo of DirectoryInfo is slow, e.g. if you are trying to access network drives/folders).
            //NOTE: selecting items through UI doesn't invoke this method.
            //So when you have explorer tree and address bar in your application and user mainly iteracts with the tree,
            //while specifying full folder path is not a common task, there should be no problems at all.

            //If it is not possible to avoid this issue, some sort of dictionary, mapping or backing storage can be used
            //to store information about loaded DriveInfo or FolderInfo, so that you will not have to iterate through the entire tree to select an item.
            InitExplorer();

            if (String.IsNullOrEmpty(value))
            {
                return;
            }

            var split =
                Path.GetFullPath(value).Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
                    StringSplitOptions.RemoveEmptyEntries);
            var drive = new DriveInfo(split[0]);

            Action<TreeViewItem, int> expand = null;
            expand = (item, index) =>
            {
                if (index > split.Length)
                {
                    return;
                }

                if (index == split.Length)
                {
                    item.IsSelected = true;
                    return;
                }

                if (!item.IsExpanded)
                {
                    item.IsExpanded = true;
                }

                var name = split[index].ToLower();

                foreach (TreeViewItem folderItem in item.Items)
                {
                    var directoryInfo = (DirectoryInfo)folderItem.Tag;
                    if (directoryInfo.Name.ToLower() == name)
                    {
                        // ReSharper disable PossibleNullReferenceException
                        // ReSharper disable AccessToModifiedClosure
                        expand(folderItem, index + 1);
                        // ReSharper restore AccessToModifiedClosure
                        // ReSharper restore PossibleNullReferenceException
                        break;
                    }
                }
            };

            foreach (TreeViewItem driveItem in Items)
            {
                var name = ((DriveInfo)driveItem.Tag).Name.ToLower();
                if (name == drive.Name.ToLower())
                {
                    expand(driveItem, 1);
                    break;
                }
            }
        }
Exemple #50
0
        /// <summary>
        /// Creates an ISO image from media (CD/DVD)
        /// </summary>
        /// <param name="source">CD/DVD</param>
        /// <param name="destination">Path where the ISO file is to be stored</param>
        /// <returns>
        /// Running = Creation in progress
        /// InvalidHandle = Invalid handle
        /// NoDevice = The source is not a medium (CD/DVD)
        /// NotEnoughMemory = Not enough disk space
        /// LimitExceeded = Source exceeds FAT32 maximum file size of 4 GB (4096 MB)
        /// NotReady = The device is not ready
        /// </returns>
        public IsoState CreateIsoFromMedia(string source, string destination)
        {
            //Is the device ready?
            if (!new DriveInfo(source).IsReady)
                return IsoState.NotReady;

            //Source CD/DVD
            if (new DriveInfo(source).DriveType != DriveType.CDRom)
                return IsoState.NoDevice;

            //Get medium size
            MediumSize = GetMediumLength(source);

            //Check disk space
            long diskSize = new DriveInfo(Path.GetPathRoot(destination)).AvailableFreeSpace;

            if (diskSize <= MediumSize)
                return IsoState.NotEnoughMemory;

            //Check capacity of > 4096 MB (NTFS)
            if (!CheckNTFS(destination) && MediumSize >= LIMIT)
                return IsoState.LimitExceeded;

            //Create handle
            Handle = Win32.CreateFile(source);

            if (!string.IsNullOrEmpty(destination))
                PathToIso = destination;

            //If invalid or closed handle
            if (Handle.IsInvalid || Handle.IsClosed)
                return IsoState.InvalidHandle;

            //Create thread to create the ISO file
            bgCreator.RunWorkerAsync();

            return IsoState.Running;
        }
        public bool MountDrive(DriveInfo drive)
        {
            if (ValidPassword(drive))
            {
                CryptoMirror crptMirr = new CryptoMirror(drive.Root, drive.Letter, drive.Label);
                Thread newThread = new Thread(CreateDrive);
                newThread.Start(crptMirr);
                threads.Add(drive.Letter, newThread);

                appSettings.UnMountDrive(drive, true);
                DrivesList = appSettings.GetDrives();
                return true;
            }

            return false;
        }
Exemple #52
0
        public FileDialog(FileDialogMode mode)
        {
            _mode = mode;

            BuildUI();

            switch (mode)
            {
            case FileDialogMode.OpenFile:
                Title = "Open File...";
                break;

            case FileDialogMode.SaveFile:
                Title = "Save File...";
                break;

            case FileDialogMode.ChooseFolder:
                Title = "Choose Folder...";
                break;
            }

            AutoAddFilterExtension = true;

            if (mode == FileDialogMode.ChooseFolder)
            {
                _textBlockFileName.Visible = false;
                _textFieldFileName.Visible = false;
            }

            _splitPane.SetSplitterPosition(0, 0.3f);

            _buttonBack.Background    = null;
            _buttonForward.Background = null;
            _buttonParent.Background  = null;

            _listBoxPlaces.Background = null;

            _buttonBack.Image    = DefaultAssets.UITextureRegionAtlas["icon-arrow-left"];
            _buttonForward.Image = DefaultAssets.UITextureRegionAtlas["icon-arrow-right"];
            _buttonParent.Image  = DefaultAssets.UITextureRegionAtlas["icon-folder-parent"];

            var homePath = (Environment.OSVersion.Platform == PlatformID.Unix ||
                            Environment.OSVersion.Platform == PlatformID.MacOSX)
                                ? Environment.GetEnvironmentVariable("HOME")
                                : Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");

            var iconFolder = DefaultAssets.UITextureRegionAtlas["icon-folder"];

            var places = new List <string>
            {
                homePath
            };

            foreach (var f in Folders)
            {
                places.Add(Path.Combine(homePath, f));
            }

            foreach (var p in places)
            {
                if (!Directory.Exists(p))
                {
                    continue;
                }

                _listBoxPlaces.Items.Add(new ListItem(Path.GetFileName(p), null, p)
                {
                    Image            = iconFolder,
                    ImageTextSpacing = ImageTextSpacing
                });
            }

            if (_listBoxPlaces.Items.Count > 0)
            {
                SetFolder((string)_listBoxPlaces.Items[0].Tag, false);
            }

            _listBoxPlaces.Items.Add(new ListItem
            {
                IsSeparator = true
            });

            var drives = DriveInfo.GetDrives();

            var iconDrive = DefaultAssets.UITextureRegionAtlas["icon-drive"];

            foreach (var d in drives)
            {
                if (d.DriveType == DriveType.Ram)
                {
                    continue;
                }

                try
                {
                    var s = d.RootDirectory.Name;

                    if (!string.IsNullOrEmpty(d.VolumeLabel) && d.VolumeLabel != d.RootDirectory.Name)
                    {
                        s += " (" + d.VolumeLabel + ")";
                    }

                    _listBoxPlaces.Items.Add(new ListItem(s, null, d.RootDirectory.Name)
                    {
                        Image            = iconDrive,
                        ImageTextSpacing = ImageTextSpacing
                    });
                }
                catch (Exception)
                {
                }
            }

            _listBoxPlaces.SelectedIndexChanged += OnPlacesSelectedIndexChanged;

            _gridFiles.SelectionBackground      = DefaultAssets.UITextureRegionAtlas["tree-selection"];
            _gridFiles.SelectionHoverBackground = DefaultAssets.UITextureRegionAtlas["button-over"];
            _gridFiles.SelectedIndexChanged    += OnGridFilesSelectedIndexChanged;
            _gridFiles.TouchDoubleClick        += OnGridFilesDoubleClick;

            _buttonParent.Click += OnButtonParent;

            _textFieldFileName.TextChanged += (s, a) => UpdateEnabled();

            _buttonBack.Click    += OnButtonBack;
            _buttonForward.Click += OnButtonForward;

            UpdateEnabled();
        }
        public bool UnmountDrive(DriveInfo drive)
        {
            try
            {
                if (drive.Mounted)
                {
                    DokanNet.DokanUnmount(drive.Letter);
                    threads[drive.Letter].Abort();
                    threads.Remove(drive.Letter);

                    appSettings.UnMountDrive(drive, false);
                    DrivesList = appSettings.GetDrives();
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                return false;
            }

            return true;
        }
Exemple #54
0
 public DriveData(DriveInfo drive)
 {
     this.drive = drive;
 }
        private string GetDrivePassword(DriveInfo drive)
        {
            XmlDriveSettings dSettings = new XmlDriveSettings(drive.Root);
            string password = dSettings.ReadPassword();
            byte[] encPassword = encryptor.EnDecrypt(false, Encoding.Default.GetBytes(password));
            password = Encoding.Default.GetString(encPassword);

            return password;
        }
        private int Mount(string passPhrase, IList <string> userNames)
        {
            var mountSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections[MountSection.Name] as MountSection;

            if (mountSection == null)
            {
                throw new ConfigurationErrorsException("Mount configuration missing");
            }

            settingsPassPhrase = passPhrase;

            try {
                using (var logFactory = new LogFactory()) {
                    logger = logFactory.GetCurrentClassLogger();
                    var factory = InitializeCloudDriveFactory(mountSection.LibPath);
                    using (var tokenSource = new CancellationTokenSource()) {
                        var tasks = new List <Task>();
                        foreach (var driveElement in mountSection.Drives.Where(d => !userNames.Any() || userNames.Contains(d.UserName)))
                        {
                            var drive = factory.CreateCloudDrive(driveElement.Schema, driveElement.UserName, driveElement.Root, new CloudDriveParameters()
                            {
                                ApiKey = driveElement.ApiKey, EncryptionKey = driveElement.EncryptionKey, Parameters = driveElement.GetParameters()
                            });
                            if (!drive.TryAuthenticate())
                            {
                                var displayRoot = drive.DisplayRoot;
                                drive.Dispose();
                                logger.Warn($"Authentication failed for drive '{displayRoot}'");
                                continue;
                            }

                            var operations = new CloudOperations(drive, logger);

                            // HACK: handle non-unique parameter set of DokanOperations.Mount() by explicitely specifying AllocationUnitSize and SectorSize
                            tasks.Add(Task.Run(() => operations.Mount(driveElement.Root, DokanOptions.RemovableDrive | DokanOptions.MountManager | DokanOptions.CurrentSession, mountSection.Threads, 1100, TimeSpan.FromSeconds(driveElement.Timeout != 0 ? driveElement.Timeout : 20), null, 512, 512), tokenSource.Token));

                            var driveInfo = new DriveInfo(driveElement.Root);
                            while (!driveInfo.IsReady)
                            {
                                Thread.Sleep(10);
                            }
                            logger.Info($"Drive '{drive.DisplayRoot}' mounted successfully.");
                        }

                        Console.WriteLine("Press CTRL-BACKSPACE to clear log, any other key to unmount drives");
                        while (true)
                        {
                            var keyInfo = Console.ReadKey(true);
                            if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.Backspace)
                            {
                                Console.Clear();
                            }
                            else
                            {
                                break;
                            }
                        }

                        tokenSource.Cancel();

                        return(0);
                    }
                }
            } catch (Exception ex) {
                Console.Error.WriteLine($"{ex.GetType().Name}: {ex.Message}");
                return(-1);
            } finally {
                foreach (var driveElement in mountSection.Drives.Cast <DriveElement>())
                {
                    Dokan.Unmount(driveElement.Root[0]);
                }
                UIThread.Shutdown();
            }
        }
Exemple #57
0
        private static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            #region Logging

            Log.Logger = new LoggerConfiguration()
#if DEBUG
                         .MinimumLevel.Debug()
#else
                         .MinimumLevel.Information()
#endif
                         .WriteTo.Console()
                         .WriteTo.RollingFile("Logs\\Shibari.Dom.Server-{Date}.log")
                         .CreateLogger();

            #endregion

            #region Global exception handler

            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                Log.Fatal("Unhandled exception: {Exception}", (Exception)eventArgs.ExceptionObject);
            };

            #endregion

            Log.Information("Launching Shibari, version: {Version}",
                            Assembly.GetExecutingAssembly().GetName().Version);

            #region Self-Unblocking

            var domRoot   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".";
            var rootDrive = new DriveInfo(domRoot);

            // ADS is only present on NTFS formatted drives
            if (rootDrive.DriveFormat.Equals("NTFS", StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    var files = Directory.GetFiles(domRoot, "*.dll", SearchOption.AllDirectories);

                    foreach (var fileInfo in files.Select(f => new FileInfo(f)))
                    {
                        if (!fileInfo.AlternateDataStreamExists("Zone.Identifier"))
                        {
                            continue;
                        }
                        Log.Information("Removing Zone.Identifier from file {File}", fileInfo.Name);
                        var ads = fileInfo.GetAlternateDataStream("Zone.Identifier", FileMode.Open);
                        ads.Delete();
                    }
                }
                catch (Exception ex)
                {
                    Log.Fatal("Error unblocking files, program may be unusable, contact support! {@Exception}", ex);
                    Process.Start("https://forums.vigem.org/topic/375/manually-unblock-shibari-archive");
                    Console.WriteLine("Press any key to escape the madness! :)");
                    Console.ReadKey();
                    return;
                }
            }
            else
            {
                Log.Information("Process started from {Filesystem} formatted drive, no unblocking necessary",
                                rootDrive.DriveFormat);
            }

            #endregion

            #region Single instance check & hosting

            // https://stackoverflow.com/a/229567

            // get application GUID as defined in AssemblyInfo.cs
            var appGuid = Guid.Parse("{E7A7AB5E-2C61-4677-9946-427A6B8E0C53}");

            // unique id for global mutex - Global prefix means it is global to the machine
            var mutexId = $"Global\\{{{appGuid}}}";

            // Need a place to store a return value in Mutex() constructor call
            bool createdNew;

            // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
            // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
            var allowEveryoneRule =
                new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid
                                                           , null)
                                    , MutexRights.FullControl
                                    , AccessControlType.Allow
                                    );
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
            using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
            {
                // edited by acidzombie24
                var hasHandle = false;
                try
                {
                    try
                    {
                        // note, you may want to time out here instead of waiting forever
                        // edited by acidzombie24
                        // mutex.WaitOne(Timeout.Infinite, false);
                        hasHandle = mutex.WaitOne(200, false);
                        if (hasHandle == false)
                        {
                            throw new ApplicationException(
                                      "This application can only be run once, please check if the service may be running already");
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact that the mutex was abandoned in another process,
                        // it will still get acquired
                        hasHandle = true;
                    }

                    HostFactory.Run(x =>
                    {
                        x.Service <BusEmulatorHubService>(s =>
                        {
                            s.ConstructUsing(name => new BusEmulatorHubService());
                            s.WhenStarted(tc => tc.Start());
                            s.WhenStopped(tc => tc.Stop());
                        });
                        x.RunAsLocalSystem();

                        x.SetDescription("Manages AirBender, FireShock & BthPS3 Devices.");
                        x.SetDisplayName("Shibari Dom Server");
                        x.SetServiceName("Shibari.Dom.Server");
                    });
                }
                finally
                {
                    // edited by acidzombie24, added if statement
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }

            #endregion
        }
Exemple #58
0
        private void populateComboBoxFromDirectory(string directory)
        {
            lookInComboBox.SuspendLayout();

            // TODO: get network share info

            // remove old drive entries
            while (lookInComboBox.Items.Count > 4)
            {
                lookInComboBox.Items.RemoveAt(4);
            }

            DirectoryInfo dirInfo = new DirectoryInfo(directory);

            // fill tree view with special locations and drives
            TreeNode myComputerNode = lookInComboBox.Items[3] as TreeNode;
            int      driveCount     = 0;

            foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
            {
                // skip this drive if there's a problem accessing its properties
                try { var foo = driveInfo.VolumeLabel; } catch { continue; }

                string label;
                string sublabel = driveInfo.Name;
                driveReadiness[sublabel] = driveInfo.IsReady;
                int imageIndex;
                ++driveCount;
                switch (driveInfo.DriveType)
                {
                case DriveType.Fixed:
                    if (driveInfo.VolumeLabel.Length > 0)
                    {
                        label = driveInfo.VolumeLabel;
                    }
                    else
                    {
                        label = "Local Drive";
                    }
                    imageIndex = 5;
                    break;

                case DriveType.CDRom:
                    if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0)
                    {
                        label = driveInfo.VolumeLabel;
                    }
                    else
                    {
                        label = "Optical Drive";
                    }
                    imageIndex = 6;
                    break;

                case DriveType.Removable:
                    if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0)
                    {
                        label = driveInfo.VolumeLabel;
                    }
                    else
                    {
                        label = "Removable Drive";
                    }
                    imageIndex = 6;
                    break;

                case DriveType.Network:
                    label      = "Network Share";
                    imageIndex = 7;
                    break;

                default:
                    label      = "";
                    imageIndex = 8;
                    break;
                }
                TreeNode driveNode;
                if (label.Length > 0)
                {
                    driveNode = myComputerNode.Nodes.Add(sublabel, String.Format("{0} ({1})", label, sublabel), imageIndex, imageIndex);
                }
                else
                {
                    driveNode = myComputerNode.Nodes.Add(sublabel, sublabel, imageIndex, imageIndex);
                }
                driveNode.Tag = sublabel;
                lookInComboBox.Items.Insert(3 + driveCount, driveNode);

                if (sublabel == dirInfo.Root.Name)
                {
                    List <string> branches = new List <string>(directory.Split(new char[] {
                        Path.DirectorySeparatorChar,
                        Path.AltDirectorySeparatorChar
                    },
                                                                               StringSplitOptions.RemoveEmptyEntries));
                    TreeNode pathNode = driveNode;
                    for (int i = 1; i < branches.Count; ++i)
                    {
                        ++driveCount;
                        pathNode     = pathNode.Nodes.Add(branches[i], branches[i], 8, 8);
                        pathNode.Tag = String.Join(Path.DirectorySeparatorChar.ToString(),
                                                   branches.GetRange(0, i).ToArray());
                        lookInComboBox.Items.Insert(3 + driveCount, pathNode);
                    }
                    lookInComboBox.SelectedIndex = 3 + driveCount;
                }
            }
            //desktopNode.Nodes.Add( "My Network Places", "My Network Places", 4, 4 ).Tag = "My Network Places";

            lookInComboBox.DropDownHeight = lookInComboBox.Items.Count * 18 + 2;

            lookInComboBox.ResumeLayout();
        }
Exemple #59
0
        static void Main(string[] args)
        {
            /*Getting drive info*/
            DriveInfo info = new DriveInfo(@"c:\");

            Console.WriteLine("Drive name is: {0}", info.Name);
            Console.WriteLine("Drive type is: {0}", info.DriveType);
            Console.WriteLine($"Drive free space is: {info.TotalFreeSpace}");
            Console.WriteLine($"Drive size is: {info.TotalSize}");
            Console.WriteLine($"Drive available free space is: {info.AvailableFreeSpace}");

            Console.WriteLine("*********************");

            DriveInfo[] driveinfo = DriveInfo.GetDrives();
            foreach (DriveInfo drive in driveinfo)
            {
                Console.WriteLine($"Drive name: {drive.Name}");
            }

            /*Creating directories*/

            /*
             * DirectoryInfo directory = Directory.CreateDirectory("tochi/program");
             * DirectoryInfo directoryInfo = new DirectoryInfo("chichi/school");
             * directoryInfo.Create();
             */

            /*Test if directory exists*/
            if (Directory.Exists("chuks"))
            {
                Console.WriteLine("'Chuks' directory exists");
            }
            DirectoryInfo dirInfo = new DirectoryInfo("chichi/school");

            if (dirInfo.Exists)
            {
                Console.WriteLine("'chichi/school' directory exists");
            }


            /*Moving a directory*/

            /*
             * Directory.Move("tochi", "chuks/tochi");
             * DirectoryInfo dirInfo1 = new DirectoryInfo("chichi");
             * dirInfo1.MoveTo("school/chichi");
             */

            /*Listing file names with Directory class*/
            Console.WriteLine("***Listing file names with Directory class***");
            string[] fileNames = Directory.GetFiles("school/chichi");
            foreach (string fileName in fileNames)
            {
                Console.WriteLine($"File Name: {fileName}");
            }

            /*Listing file infos with DirectoryInfo class*/
            Console.WriteLine("***Listing file info with DirectoryInfo class***");
            DirectoryInfo dirInfo2 = new DirectoryInfo("school/chichi");

            FileInfo[] fileInfos = dirInfo2.GetFiles();
            foreach (FileInfo fileinfo in fileInfos)
            {
                Console.WriteLine($"File Name: {fileinfo.Name}");
                Console.WriteLine($"File Length: {fileinfo.Length}");
                Console.WriteLine($"File Creation Time: {fileinfo.CreationTime}");
                Console.WriteLine($"Fle Directory: {fileinfo.Directory}");
                Console.WriteLine($"File Directory Name: {fileinfo.DirectoryName}");
                Console.WriteLine("-----");
            }

            /*Create Write, Read and Copy file*/
            Console.WriteLine("**File Create, Write Read Operation***");
            //FileOperation1();

            /*FileStream write Operation using File (static) class*/
            FileStreamWriteOperation();

            /*Using the FileStream class to write*/
            FileStreamWrite("C Sharp has been a bit of fun to learn");

            /*StringWriter and StringReader class */
            StringWriteRead();

            /*BinaryWriter and BinaryReader*/
            BinaryWriteRead();

            Console.WriteLine("***Communication over a network****");
            /*WebRequest and WebResponse class of System.Net*/
            //WebStream();

            /*File I\O Asynchronous methods*/
            ReadWriteAsync();

            /*StreamReader*/
            streamRead1();
            streamRead2();

            Console.ReadLine();
        }
Exemple #60
0
        public VolumeScanner(VolumeDatabase db, DriveInfo drive)
        {
            this.scanCompleted = false;
            this.database = db;
            this.newVolume = null;

            infoIcon	= RenderIcon(Icons.Icon.Stock_DialogInfo,	   ICON_SIZE);
            warningIcon = RenderIcon(Icons.Icon.Stock_DialogWarning,   ICON_SIZE);
            errorIcon	= RenderIcon(Icons.Icon.Stock_DialogError,	   ICON_SIZE);

            mdps = null;

            if (App.Settings.ScannerExtractMetaData &&
                (VolumeProber.ProbeVolume(drive) == VolumeProber.VolumeProbeResult.Filesystem)) {

                mdps = new MetadataProvider[] {
                    new TagLibMetadataProvider(),
                    new ArchiveMetadataProvider()
                };
            }

            // setup scanner options
            ScannerOptions[] opts = new ScannerOptions[2] {

                new FilesystemScannerOptions() {
                    BufferSize			= App.Settings.ScannerBufferSize,
                    ComputeHashs		= App.Settings.ScannerComputeHashs,
                    DiscardSymLinks		= App.Settings.ScannerDiscardSymLinks,
                    GenerateThumbnails	= App.Settings.ScannerGenerateThumbnails,
                    MetadataProviders	= mdps,
                    DbDataPath			= PathUtil.GetDbDataPath(database)
                },

                new AudioCdScannerOptions() {
                    EnableMusicBrainz = App.Settings.ScannerEnableMusicBrainz
                }
            };

            scanner = VolumeProber.GetScannerForVolume(drive, database, opts);

            // scanner eventhandlers
            scanner.BeforeScanItem	  += scanner_BeforeScanItem;
            scanner.ScannerWarning	  += scanner_ScannerWarning;
            scanner.Error			  += scanner_Error;
            scanner.ScanCompleted	  += scanner_ScanCompleted;

            /* volumedatabase event handlers */
            database.BeginWriteAccess	+= database_BeginWriteAccess;
            database.EndWriteAccess		+= database_EndWriteAccess;

            // must be called _after_ scanner instanciation
            // (requires scanner.VolumeInfo.GetVolumeType())
            BuildGui();
            InitTreeView();

            scannerLog = new StringBuilder();
            timer = new StatusUpdateTimer(this);

            try {
                /* NOTE: make sure the timer will be removed properly later,
                 * or it keeps running, even if this window has been closed. */
                timer.Install();

                string tmp;
                // e.g. GIO network 'drives' do not have a devicefile
                if (string.IsNullOrEmpty(drive.Device))
                    tmp = S._("Scanning started.");
                else
                    tmp = string.Format(S._("Scanning of drive '{0}' started."), drive.Device);

                UpdateLog(LogIcon.Info, tmp);

                switch (scanner.VolumeInfo.GetVolumeType()) {
                    case VolumeType.FileSystemVolume:
                        UpdateLog(LogIcon.Info, string.Format(S._("Options: generate thumbs: {0}, extract metadata: {1}, discard symlinks: {2}, hashing: {3}."),
                                                              BoolToStr(App.Settings.ScannerGenerateThumbnails),
                                                              BoolToStr(App.Settings.ScannerExtractMetaData),
                                                              BoolToStr(App.Settings.ScannerDiscardSymLinks),
                                                              BoolToStr(App.Settings.ScannerComputeHashs)));
                        break;
                    case VolumeType.AudioCdVolume:
                        UpdateLog(LogIcon.Info, string.Format(S._("Options: MusicBrainz enabled: {0}"),
                                                          BoolToStr(App.Settings.ScannerEnableMusicBrainz)));
                        break;
                    default:
                        throw new NotImplementedException(string.Format("Missing options output for scannertyp {0}", scanner.GetType()));
                }

                if (scanner.VolumeInfo.GetVolumeType() == VolumeType.FileSystemVolume) {
                    // copy already known volume data into the editor
                    volEditor.ArchiveNo = scanner.VolumeInfo.ArchiveNo;
                    volEditor.Title = scanner.VolumeInfo.Title;
                } else {
                    // other volumetypes have no useful data yet (e.g. AudioCD data may be queried from musicbrainz.org),
                    // so disable the editor and re-enable it and fill in the data when scanning has been completed.
                    volEditor.Sensitive = false;
                }

                // start scanning on a new thread and return immediately
                scanner.RunAsync();
            } catch {
                timer.Remove();
                throw;
            }
        }