private void RefreshValues() { System.IO.DriveInfo drive = GetDriveInfo(); lblArchiveName.Text = this.ArchiveName + " - " + drive.VolumeLabel + " (" + _Drive + ":)"; lblSize.Text = GetDiskSizeText(drive); diskSpaceProgress.Value = GetDiskSpaceUsedPercent(drive); }
private static string TryResolveIsolationPath(string defaultIfNotFound) { System.IO.DriveInfo mostLikelyDrive = null; System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); foreach (System.IO.DriveInfo drive in drives) { try { if (!drive.IsReady) { continue; } if (mostLikelyDrive == null || mostLikelyDrive.AvailableFreeSpace < drive.AvailableFreeSpace || defaultIfNotFound.StartsWith(drive.RootDirectory.FullName.Substring(0, 3))) { mostLikelyDrive = drive; } } catch (Exception ex) { ex.Log(); } } return(mostLikelyDrive == null ? defaultIfNotFound : mostLikelyDrive.RootDirectory.FullName); }
static void Main() { // Start with drives if you have to search the entire computer. string[] drives = System.Environment.GetLogicalDrives(); foreach (string dr in drives) { System.IO.DriveInfo di = new System.IO.DriveInfo(dr); // Here we skip the drive if it is not ready to be read. This // is not necessarily the appropriate action in all scenarios. if (!di.IsReady) { Console.WriteLine("The drive {0} could not be read", di.Name); continue; } System.IO.DirectoryInfo rootDir = di.RootDirectory; WalkDirectoryTree(rootDir); } // Write out all the files that could not be processed. Console.WriteLine("Files with restricted access:"); foreach (string s in log) { Console.WriteLine(s); } // Keep the console window open in debug mode. Console.WriteLine("Press any key"); Console.ReadKey(); }
private void button6_Click(object sender, EventArgs e) { SelectDriveForm sdf = new SelectDriveForm(); if (sdf.ShowDialog() == DialogResult.OK) { // check if a removable drive System.IO.DriveInfo di = sdf.SelectedDrive; if (di.DriveType != System.IO.DriveType.Removable) { if (di.DriveType == System.IO.DriveType.Ram) { MessageBox.Show("You have selected a RAM drive. This is not allowed."); return; } else if (di.DriveType == System.IO.DriveType.NoRootDirectory) { MessageBox.Show("The Selected drive doesn't have a root Directory!"); return; } DialogResult r = MessageBox.Show("Warning: The drive you have selected isn't a removable drive.\nContinue?", "OH NOES!", MessageBoxButtons.YesNo); if (r == System.Windows.Forms.DialogResult.No) { return; } } // generate Drive info IITPlaylist device = GetPlaylistNameForm.InputBox(); Device newDevice = new Device(device, di); listBox1.Items.Add(newDevice.Name.ToUpper() + " (" + newDevice.iTunesPlaylist.Name + ")"); ManagedDrives.Add(newDevice); //MessageBox.Show("To put songs on your device, drag them onto the playlist, \n" + "Then press 'sync'"); } }
/// <summary>Triggers the event when change on device occured.</summary> /// <param name="sender"></param> /// <param name="e"></param> private void MediaEventArrived(object sender, EventArrivedEventArgs e) { // Get the Event object and display it var pd = e.NewEvent.Properties["TargetInstance"]; DriveStatus driveStatus = _mDriveStatus; var usbDriveInfo = new USBDriveInfo(); { var mbo = pd.Value as ManagementBaseObject; if (mbo != null) { var info = new System.IO.DriveInfo((string)mbo.Properties["DeviceID"].Value); driveStatus = info.IsReady ? DriveStatus.Inserted : DriveStatus.Ejected; usbDriveInfo.DriveName = (string)mbo.Properties["DeviceID"].Value; } usbDriveInfo.DriveStatus = driveStatus; } if (driveStatus != _mDriveStatus) { _mDriveStatus = driveStatus; if (null != MediaWatcher) { MediaWatcher(sender, usbDriveInfo); } } }
static void Main() { // Начните с драйвов если нужно исследовать весь копьютер. string[] drives = System.Environment.GetLogicalDrives(); foreach (string dr in drives) { System.IO.DriveInfo di = new System.IO.DriveInfo(dr); // Здесь мы пропускаем драйв если нет необходимости его читать. // Во многих случаях это действием является неподходящим. if (!di.IsReady) { Console.WriteLine("The drive {0} could not be read", di.Name); continue; } System.IO.DirectoryInfo rootDir = di.RootDirectory; WalkDirectoryTree(rootDir); } // Выписывает все файлы требующие обработки. Console.WriteLine("Files with restricted access:"); foreach (string s in log) { Console.WriteLine(s); } // Содержит консоль в режиме отладки. Console.WriteLine("Press any key"); Console.ReadKey(); }
public RepositoryTestFixture() { //drop and recreate the test Db every time the tests are run. // string dbDir = testContext.TestDeploymentDir; string dbDir = System.IO.Path.GetTempPath(); string pathRoot = System.IO.Path.GetPathRoot(dbDir); var driveInfo = new System.IO.DriveInfo(pathRoot); if (driveInfo.DriveType == System.IO.DriveType.Network) { // a db file doesn't work on network-drive dbDir = System.IO.Path.GetTempPath(); } string dbFile = $@"{dbDir}\CNCLibTest.db"; SqliteDatabaseTools.DatabaseFile = dbFile; var dbContext = CreateDbContext(); dbContext.Database.EnsureDeleted(); dbContext.InitializeDatabase(); new TestDataImporter(dbContext).Import(); dbContext.SaveChanges(); }
public Directory GetLogicalDrives() { Directory dir; List <DirectoryData> drData = new List <DirectoryData>(); List <string> drives = System.Environment.GetLogicalDrives().ToList <string>(); foreach (var dr in drives) { System.IO.DriveInfo di = new System.IO.DriveInfo(dr); if (di.IsReady) { drData.Add(new DirectoryData() { Name = di.Name, FullName = "...", IsFolder = 1, Size = di.TotalSize }); } } dir = new Directory() { path = "...", data = drData }; return(dir); }
private PSDriveInfo NewDrive(System.IO.DriveInfo fsDrive) { Path name = fsDrive.Name; var iColon = fsDrive.Name.IndexOf(":"); if (iColon > 0) { name = fsDrive.Name.Substring(0, iColon); } Path description = string.Empty; Path root = fsDrive.Name; if (fsDrive.DriveType == System.IO.DriveType.Fixed) { try { description = fsDrive.VolumeLabel; root = fsDrive.RootDirectory.FullName; } catch { } } PSDriveInfo info = new PSDriveInfo(name, base.ProviderInfo, root, description, null); info.RemovableDrive = fsDrive.DriveType != System.IO.DriveType.Fixed; return(info); }
/// <summary> /// Gets the drive type of the given path. /// <locDE><para />Ermittelt die Laufwerksart des angegebenen Pfades.</locDE> /// </summary> /// <param name="path">The path.<locDE><para />Der Pfad.</locDE></param> /// <returns>DriveType of path.<locDE><para />DriveType des Pfades.</locDE></returns> public static System.IO.DriveType GetPathDriveType(string path) { // http://stackoverflow.com/questions/4396634/how-can-i-determine-if-a-given-drive-letter-is-a-local-mapped-usb-drive if (string.IsNullOrWhiteSpace(path)) { return(System.IO.DriveType.Unknown); } // OK, so UNC paths aren't 'drives', but this is still handy if (path.StartsWith(@"\\")) { return(System.IO.DriveType.Network); } System.IO.DriveInfo info = null; try { info = System.IO.DriveInfo.GetDrives().FirstOrDefault(x => path.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase)); } catch { } if (info == null) { return(System.IO.DriveType.Unknown); } return(info.DriveType); }
public void GetDefaultDrive() { // Get the default drive's path var drivePath = new System.IO.DirectoryInfo(Environment.SystemDirectory).Root.Name; var driveInfoPath = new System.IO.DriveInfo(drivePath); Assert.IsTrue(drivePath != null); var drive = BrowseItemFromPath.InitItem(drivePath); //// drive.LoadProperties(); Assert.IsTrue(drive != null); Assert.IsTrue(drivePath.Equals(drive.PathFileSystem, StringComparison.InvariantCulture)); Assert.IsFalse(string.IsNullOrEmpty(drive.Name)); //Assert.IsTrue(string.Compare(drive.Name, driveInfoPath.VolumeLabel, true) == 0); Assert.IsTrue(string.Compare(drive.ParseName, driveInfoPath.Name, true) == 0); Assert.IsFalse(string.IsNullOrEmpty(drive.LabelName)); Assert.IsFalse(drive.IsSpecialParseItem); Assert.IsTrue(string.IsNullOrEmpty(drive.PathSpecialItemId)); Assert.IsTrue(string.Compare(drive.ParseName, drive.PathFileSystem, true) == 0); //// Assert.IsTrue((drive.ItemType & DirectoryItemFlags.FileSystemDirectory) != 0); //// Assert.IsTrue((drive.ItemType & DirectoryItemFlags.Drive) != 0); //// Assert.IsTrue(drive.ParentIdList.Size > 0); //// Assert.IsTrue(drive.ChildIdList.Size > 0); //// Assert.IsFalse(string.IsNullOrEmpty(drive.IconResourceId)); }
private static void test() { string[] drives = System.Environment.GetLogicalDrives(); System.IO.DirectoryInfo[] subDirs = null; foreach (string dr in drives) { System.IO.DriveInfo di = new System.IO.DriveInfo(dr); // Here we skip the drive if it is not ready to be read. This // is not necessarily the appropriate action in all scenarios. if (!di.IsReady) { Console.WriteLine("The drive {0} could not be read", di.Name); continue; } System.IO.DirectoryInfo rootDir = di.RootDirectory; Console.WriteLine(di.Name); subDirs = rootDir.GetDirectories(); foreach (System.IO.DirectoryInfo dir in subDirs) { Console.WriteLine(dir.Name); // Name ir direktorijas nosaukums, bet FullName pilns nosaukums sākot no diska //Console.WriteLine(dir.FullName); } } }
private PSDriveInfo NewDrive(System.IO.DriveInfo fsDrive) { //Console.WriteLine("xxx ps00-2000-0: NewDrive is fsDrive null? " + (fsDrive == null ? "yes" : "no")); //Console.ReadKey(); Path name = fsDrive.Name; //Console.ReadKey(); //Console.WriteLine("xxx ps00-2000-2: NewDrive is fsDrive.Name null? " + (fsDrive.Name == null ? "yes" : "no")); //Console.WriteLine("xxx ps00-2000-4: name.GetDrive() " + name.GetDrive()); var iColon = fsDrive.Name.IndexOf(":"); if (iColon > 0) { name = fsDrive.Name.Substring(0, iColon); } Path description = string.Empty; Path root = fsDrive.Name; if (fsDrive.DriveType == System.IO.DriveType.Fixed) { try { description = fsDrive.VolumeLabel; root = fsDrive.RootDirectory.FullName; } catch { } } PSDriveInfo info = new PSDriveInfo(name, base.ProviderInfo, root, description, null); info.RemovableDrive = fsDrive.DriveType != System.IO.DriveType.Fixed; return(info); }
internal static bool IsRunningFromNetwork(string rootPath) { try { System.IO.DriveInfo info = new System.IO.DriveInfo(rootPath); if (info.DriveType == System.IO.DriveType.Network) { return(true); } else { return(false); } } catch { try { Uri uri = new Uri(rootPath); return(uri.IsUnc); } catch { return(false); } } }
internal USBDrive(System.IO.DriveInfo drive) { this.DriveObject = drive; this.DriveLetter = drive.Name; this.Label = drive.VolumeLabel; this.DriveFormat = drive.DriveFormat; }
/// <summary> /// 获取硬盘总大小,单位GB(默认C盘) /// </summary> /// <param name="diskFlag">硬盘盘符</param> /// <returns></returns> public static float GetTotalDiskSize(string diskFlag = "C") { System.IO.DriveInfo disk = new System.IO.DriveInfo(diskFlag); float.TryParse(disk.TotalSize.ToString(), out float diskTotalSize); float result = diskTotalSize / 1024f / 1024f / 1024f; return(result); }
public DriveInfo(System.IO.DriveInfo drive) { Name = drive.Name; Type = drive.DriveType.ToString(); Label = drive.IsReady ? drive.VolumeLabel : null; Format = drive.IsReady ? drive.DriveFormat : null; TotalBytes = drive.IsReady ? (ulong)drive.TotalSize : default(ulong?); }
private void SelectDrive(System.IO.DriveInfo di) { foreach (ToolStripMenuItem mi in mnuDrive.DropDownItems) { mi.Checked = mi.Tag == di; } LoadData(di.Name); }
/// <summary> /// 获取硬盘可用大小,单位GB(默认C盘) /// </summary> /// <param name="diskFlag">硬盘盘符</param> /// <returns></returns> public static float GetAvailableDiskSize(string diskFlag = "C") { System.IO.DriveInfo disk = new System.IO.DriveInfo(diskFlag); float.TryParse(disk.TotalFreeSpace.ToString(), out float freeTotalSize); float result = freeTotalSize / 1024f / 1024f / 1024f; return(result); }
public static void Launch() { System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\"); Console.WriteLine("Name: {0}", di.Name); Console.WriteLine("RootDirectory: {0}", di.RootDirectory); Console.WriteLine("DriveType: {0}", di.DriveType); Console.WriteLine("Drive Format: {0}", di.DriveFormat); Console.WriteLine("Volume Label: {0}", di.VolumeLabel); }
/* * [DllImport("kernel32")] * internal static extern int GetDiskFreeSpaceEx( * string lpDirectoryName, // directory name * ref ulong lpFreeBytesAvailable, // bytes available to caller * ref ulong lpTotalNumberOfBytes, // bytes on disk * ref ulong lpTotalNumberOfFreeBytes // free bytes on disk * ); */ internal static long GetFreeDiskSpace(string dir) { System.IO.DriveInfo drive = Config.GetDrive(dir); if (drive != null) { return(drive.AvailableFreeSpace); } return(-1); }
public override async Task <FileSystemResult> PopulateAsync() { IntDirectories = DriveInfo.GetDrives().Select(a => new LocalDrive(a, FS) { Parent = this }).Cast <DirectoryImplementation>().ToList(); IntDirectories.AddRange(UncPaths.Select(a => new LocalDirectory(new DirectoryInfo(a), FS))); IsPopulated = true; return(await Task.FromResult(new FileSystemResult())); }
public virtual void FromPath(DriveInfo d, string rootPath) { if (!rootPath.EndsWith("\\")) // e.g. "D:" -> "D:\" rootPath += "\\"; // throws ArgumentException if drive can't be found System.IO.DriveInfo di = new System.IO.DriveInfo(rootPath); FillDriveInfo(d, di); }
private void UpdateDiskSpace() { int diskValue = 0; string diskText = "--- GB free"; ActionCopyMoveRename activeCMAction = null; activeCMAction = GetActiveCmAction(); if (activeCMAction is null) { return; } string folder = activeCMAction.TargetFolder; DirectoryInfo toRoot = (!string.IsNullOrEmpty(folder) && !folder.StartsWith("\\\\")) ? new DirectoryInfo(folder).Root : null; if (toRoot != null) { System.IO.DriveInfo di; try { // try to get root of drive di = new System.IO.DriveInfo(toRoot.ToString()); } catch (System.ArgumentException) { di = null; } if (di != null) { int pct = (int)((1000 * di.TotalFreeSpace) / di.TotalSize); diskValue = 1000 - pct; diskText = di.TotalFreeSpace.GBMB(1) + " free"; } } DirectoryInfo toUNCRoot = (!string.IsNullOrEmpty(folder) && folder.StartsWith("\\\\")) ? new DirectoryInfo(folder).Root : null; if (toUNCRoot != null) { FileSystemProperties driveStats = FileHelper.GetProperties(toUNCRoot.ToString()); if (driveStats != null) { int pct = (int)((1000 * driveStats.AvailableBytes) / driveStats.TotalBytes); diskValue = 1000 - pct; diskText = (driveStats.AvailableBytes ?? 0).GBMB(1) + " free"; } } this.pbDiskSpace.Value = diskValue; this.txtDiskSpace.Text = diskText; }
private void LoadStorageInfo() { System.IO.DriveInfo drvinfo = new System.IO.DriveInfo(driveletter.ToString()); picimage.BackgroundImage = FilesystemIcons.GetLargeIcon(drvinfo.Name.Substring(0, 2) + @"\").ToBitmap(); //Daten eintragen lbdrivename.Text = DriveFunctions.GetVolumeLabel(driveletter) + " (" + driveletter.ToString().ToUpper() + ":)"; lbmodel.Text = DriveFunctions.GetDriveModelName(DriveFunctions.GetPartitionData(driveletter.ToString())[0]); lbdiskindex.Text = "Disk-Index: " + DriveFunctions.GetPartitionData(driveletter.ToString())[0]; lbpartindex.Text = "Partition-Index: " + DriveFunctions.GetPartitionData(driveletter.ToString())[1]; }
/// <summary> /// 磁盘监控对象 /// </summary> /// <param name="options"></param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> public DriveInfoItem(DriveInfoOptions options) : base(options) { this.options = options; this.driveInfo = new System.IO.DriveInfo(this.options.DriveName); if (this.driveInfo.IsReady == false) { throw new ArgumentException($"磁盘 {this.options.DriveName} 未准备好"); } }
public virtual void FromPath(DriveInfo d, string rootPath) { if (!rootPath.EndsWith("\\")) // e.g. "D:" -> "D:\" { rootPath += "\\"; } // throws ArgumentException if drive can't be found System.IO.DriveInfo di = new System.IO.DriveInfo(rootPath); FillDriveInfo(d, di); }
private void CDriveResourceRead() { var drive = new System.IO.DriveInfo("C"); if (drive.IsReady) { CDriveTextBlock.Text = Math.Round(drive.TotalSize / Math.Pow(2, 30), 2) - Math.Round(drive.TotalFreeSpace / Math.Pow(2, 30), 2) + "/" + Math.Round(drive.TotalSize / Math.Pow(2, 30), 2) + "TB"; } }
static void Main() { string folderName = Application.StartupPath; string pathString = System.IO.Path.Combine(folderName, "Albums"); System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\"); //System.IO.Directory.CreateDirectory(pathString); System.IO.DirectoryInfo dirInfo = di.RootDirectory; Console.WriteLine(dirInfo.Attributes.ToString()); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new AlbumDisplay()); }
private static void FillDirectoryTree(string folderName) { rootFolder = new Folder(folderName); System.IO.DriveInfo di = new System.IO.DriveInfo("C"); // Here we skip the drive if it is not ready to be read. This // is not necessarily the appropriate action in all scenarios. System.IO.DirectoryInfo rootDir = di.RootDirectory; WalkDirectoryTree(rootDir.GetDirectories("WINDOWS").FirstOrDefault(), rootFolder); rootFolder = rootFolder.Folders.FirstOrDefault(); }
private static void FillDriveInfo(DriveInfo d, System.IO.DriveInfo di) { if (di.IsReady) { d.volumeLabel = di.VolumeLabel; d.totalSize = di.TotalSize; d.filesystem = di.DriveFormat; } d.rootPath = di.RootDirectory.FullName; // should return e.g. "D:", not "D:\" d.device = d.rootPath[d.rootPath.Length - 1] == System.IO.Path.DirectorySeparatorChar ? d.rootPath.Substring(0, d.rootPath.Length - 1) : d.rootPath; d.isMounted = true; d.isReady = di.IsReady; switch (di.DriveType) { case System.IO.DriveType.CDRom: d.driveType = DriveType.CDRom; if (d.isReady) { d.hasAudioCdVolume = AudioCdWin32.IsAudioCd(d.device); } break; case System.IO.DriveType.Fixed: d.driveType = DriveType.Fixed; break; case System.IO.DriveType.Network: d.driveType = DriveType.Network; break; case System.IO.DriveType.Ram: d.driveType = DriveType.Ram; break; case System.IO.DriveType.Removable: d.driveType = DriveType.Removable; break; case System.IO.DriveType.NoRootDirectory: d.driveType = DriveType.Unknown; d.isMounted = false; break; case System.IO.DriveType.Unknown: d.driveType = DriveType.Unknown; break; } }
/// <summary> /// Gets the HD information requeried by the server. /// </summary> /// <returns>Returns JObect with the HD info.</returns> public static JObject GetHardDrive() { var harddriveinfo = new JObject(); try { var drivesarray = Environment.GetLogicalDrives(); foreach (var drive in drivesarray) { var di = new System.IO.DriveInfo(drive); if (!di.IsReady) { continue; } if ((di.DriveType != System.IO.DriveType.Fixed) && (di.DriveType != System.IO.DriveType.Removable)) { continue; } long tmpHdSize; long tmpHdFree; var name = ((di.VolumeLabel == null) || (di.VolumeLabel.Equals(String.Empty))) ? di.Name : di.VolumeLabel; name = name.Replace("\\", ""); var Size = di.TotalSize.ToString(CultureInfo.InvariantCulture); var InterfaceType = di.DriveFormat; var FreeSpace = di.TotalFreeSpace.ToString(CultureInfo.InvariantCulture); var converted = Int64.TryParse(Size, out tmpHdSize); converted = Int64.TryParse(FreeSpace, out tmpHdFree); if (converted) { tmpHdSize = tmpHdSize / 1024; //Convert to KB from Bytes tmpHdFree = tmpHdFree / 1024; } harddriveinfo["name"] = name; harddriveinfo["file_system"] = InterfaceType; harddriveinfo["file_kb"] = tmpHdSize.ToString(CultureInfo.InvariantCulture); harddriveinfo["free_size_kb"] = tmpHdFree.ToString(CultureInfo.InvariantCulture); } } catch (Exception) { Logger.Log("Error while gathering harddrive info.", LogLevel.Error); } return(harddriveinfo); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { System.IO.DriveInfo drive = new System.IO.DriveInfo(@"C:\"); lblDriveName.Text = drive.Name; lblDriveType.Text = drive.DriveType.ToString(); lblAvailableFreeSpace.Text = drive.AvailableFreeSpace.ToString(); lblDriveFormat.Text = drive.DriveFormat; lblTotalFreeSpace.Text = drive.TotalFreeSpace.ToString(); lblTotalSize.Text = drive.TotalSize.ToString(); lblVolumeLabel.Text = drive.VolumeLabel; } }
static void Main() { System.IO.DriveInfo di = new System.IO.DriveInfo("C"); // Here we skip the drive if it is not ready to be read. This // is not necessarily the appropriate action in all scenarios. System.IO.DirectoryInfo rootDir = di.RootDirectory; WalkDirectoryTree(rootDir.GetDirectories("WINDOWS").FirstOrDefault()); // Keep the console window open in debug mode. Console.WriteLine("Press any key"); Console.ReadKey(); }
internal SystemVolume(string volumeName, string deviceName, string devicePath) : base(GetFormattedVolumeName(volumeName)) { this.VolumeName = volumeName; this.DeviceName = deviceName; this.DevicePath = devicePath; if (string.IsNullOrEmpty(this.DevicePath) == false) { System.IO.DriveInfo drvInfo = new System.IO.DriveInfo(this.DevicePath); try { this.VolumeSize = drvInfo.TotalSize; } catch (Exception ) { this.VolumeSize = null; } } }
public IEnumerable<Models.DriveUsage> GetDriveStatistics() { var config = new Models.Configuration(); Dictionary<char, Models.DriveUsage> drives = new Dictionary<char, Models.DriveUsage>(); // add live tv buffer string liveTvBufferDir = config.LiveTvBufferDirectory; var liveTvDriveInfo = new System.IO.DriveInfo(liveTvBufferDir.Substring(0, 1)); drives.Add((char)1, new Models.DriveUsage() { Name = "Live TV Buffer", Size = liveTvDriveInfo.TotalSize, FreeSpace = liveTvDriveInfo.TotalFreeSpace, Used = liveTvDriveInfo.TotalSize - liveTvDriveInfo.TotalFreeSpace, RecordingsSize = Size(new System.IO.DirectoryInfo(liveTvBufferDir)) }); foreach (var rd in Models.RecordingDirectory.LoadForUser(GetUser().Oid, true)) { if (Regex.IsMatch(rd.Path, @"^[c-zC-Z]:\\")) { char drive = rd.Path[0]; if (!drives.ContainsKey(drive)) { var driveInfo = new System.IO.DriveInfo(drive.ToString()); drives.Add(drive, new Models.DriveUsage() { Name = drive.ToString().ToUpper() + " Drive Recordings", Size = driveInfo.TotalSize, FreeSpace = driveInfo.TotalFreeSpace, Used = driveInfo.TotalSize - driveInfo.TotalFreeSpace }); } drives[drive].RecordingsSize += Size(new System.IO.DirectoryInfo(rd.Path)); } } return drives.Values; }
internal static bool IsRunningFromNetwork(string rootPath) { try { System.IO.DriveInfo info = new System.IO.DriveInfo(rootPath); if (info.DriveType == System.IO.DriveType.Network) return true; else return false; } catch { try { Uri uri = new Uri(rootPath); return uri.IsUnc; } catch { return false; } } }
/// <summary> /// Gets the hard drive details /// </summary> private void GetHardDrive() { try { var drivesarray= Environment.GetLogicalDrives(); foreach (var drive in drivesarray) { var di = new System.IO.DriveInfo(drive); if (!di.IsReady) continue; if ((di.DriveType != System.IO.DriveType.Fixed) && (di.DriveType != System.IO.DriveType.Removable)) continue; long tmpHdSize; long tmpHdFree; _harddrive.Name = ((di.VolumeLabel == null) || (di.VolumeLabel.Equals(String.Empty))) ? di.Name : di.VolumeLabel; _harddrive.Name = _harddrive.Name.Replace("\\", ""); _harddrive.Size = di.TotalSize.ToString(CultureInfo.InvariantCulture); _harddrive.InterfaceType = di.DriveFormat; _harddrive.FreeSpace = di.TotalFreeSpace.ToString(CultureInfo.InvariantCulture); var converted = Int64.TryParse(_harddrive.Size, out tmpHdSize); converted = Int64.TryParse(_harddrive.FreeSpace, out tmpHdFree); if (converted) { tmpHdSize = tmpHdSize / 1024; //Convert to KB from Bytes tmpHdFree = tmpHdFree / 1024; } _harddrive.Size = tmpHdSize.ToString(CultureInfo.InvariantCulture); _harddrive.FreeSpace = tmpHdFree.ToString(CultureInfo.InvariantCulture); _hDlist.Add(_harddrive); } } catch (Exception e) { Logger.Log("Could not access file system data in order to obtain HardDrive Info", LogLevel.Error); Logger.LogException(e); } /* ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); ManagementObjectCollection myobject = searcher.Get(); foreach (ManagementObject item in myobject) { long tmpHDSize = 0; harddrive.InterfaceType = (item["InterfaceType"] != null) ? item["InterfaceType"].ToString() : String.Empty; string name = (item["Name"] != null) ? item["Name"].ToString() : String.Empty; Match match = Regex.Match(name, @"[0-9a-zA-Z]+"); if (match.Success) { string key = match.Groups[0].Value; harddrive.Name = key; } else { harddrive.Name = String.Empty; } string size = (item["size"] != null) ? item["size"].ToString() : String.Empty; bool converted = Int64.TryParse(size, out tmpHDSize); if(converted) tmpHDSize = tmpHDSize / 1024; //Convert to KB from Bytes harddrive.Size = tmpHDSize.ToString(); //Gather Results and store on List of type HD HDlist.Add(harddrive); } * */ }
/// <summary>Triggers the event when change on device occured.</summary> /// <param name="sender"></param> /// <param name="e"></param> private void MediaEventArrived( object sender, EventArrivedEventArgs e ) { // Get the Event object and display it PropertyData pd = e.NewEvent.Properties["TargetInstance"]; DriveStatus driveStatus = this.m_driveStatus; if( pd != null ) { ManagementBaseObject mbo = pd.Value as ManagementBaseObject; System.IO.DriveInfo info = new System.IO.DriveInfo( (string)mbo.Properties["DeviceID"].Value ); driveStatus = info.IsReady ? DriveStatus.Inserted : DriveStatus.Ejected; } if( driveStatus != this.m_driveStatus ) { this.m_driveStatus = driveStatus; if( null != MediaWatcher ) { MediaWatcher( sender, driveStatus ); } } }
public long TotalSpace(string disc) { var d = new System.IO.DriveInfo(disc); return d.TotalSize; }
protected override PSDriveInfo NewDrive(PSDriveInfo drive) { try { var driveInfo = new System.IO.DriveInfo(System.IO.Path.GetPathRoot(drive.Root)); if (driveInfo.DriveType == System.IO.DriveType.Fixed) { return (ItemExists(drive.Root) && IsItemContainer(drive.Root)) ? drive : null; } return drive; } catch { } return null; }
public static String FindBackupDrive() { try { String[] Drives = Environment.GetLogicalDrives(); for (int i = Drives.Length - 1; i >= 0; i--) { String Root = Drives[i]; if (Root.Length > 3) continue; if (String.CompareOrdinal(Root, Settings.LargestDriveLetter) <= 0 && String.CompareOrdinal(Root, Settings.SmallestDriveLetter) >= 0 && System.IO.File.Exists(Root + "BackupDrive")) { System.IO.DriveInfo DriveInfo = new System.IO.DriveInfo(Drives[i]); if (DriveInfo.DriveFormat.ToLower() != "ntfs") { HelperFunctions.ShowMessage(Translations.Get("WrongFileSystem1") + Root + Translations.Get("WrongFileSystem2"), "RoboG"); } else { return Root; } } else if (String.CompareOrdinal(Root, Settings.SmallestDriveLetter) < 0) { return null; } } } catch (Exception ex) { HelperFunctions.ShowError(ex); } return null; }
private void RescanDrives() { TargetDrive.Items.Clear(); if (!Library.Utility.Utility.IsClientLinux) for (char i = 'A'; i < 'Z'; i++) { try { System.IO.DriveInfo di = new System.IO.DriveInfo(i.ToString()); if (di.DriveType == System.IO.DriveType.Removable) TargetDrive.Items.Add(i.ToString() + ":"); } catch { } } }
static void Main() { // You can also use System.Environment.GetLogicalDrives to // obtain names of all logical drives on the computer. System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\"); Console.WriteLine(di.TotalFreeSpace); Console.WriteLine(di.VolumeLabel); // Get the root directory and print out some information about it. System.IO.DirectoryInfo dirInfo = di.RootDirectory; Console.WriteLine(dirInfo.Attributes.ToString()); // Get the files in the directory and print out some information about them. System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*"); foreach (System.IO.FileInfo fi in fileNames) { Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length); } // Get the subdirectories directly that is under the root. // See "How to: Iterate Through a Directory Tree" for an example of how to // iterate through an entire tree. System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*"); foreach (System.IO.DirectoryInfo d in dirInfos) { Console.WriteLine(d.Name); } // The Directory and File classes provide several static methods // for accessing files and directories. // Get the current application directory. string currentDirName = System.IO.Directory.GetCurrentDirectory(); Console.WriteLine(currentDirName); // Get an array of file names as strings rather than FileInfo objects. // Use this method when storage space is an issue, and when you might // hold on to the file name reference for a while before you try to access // the file. string[] files = System.IO.Directory.GetFiles(currentDirName, "*.txt"); foreach (string s in files) { // Create the FileInfo object only when needed to ensure // the information is as current as possible. System.IO.FileInfo fi = null; try { fi = new System.IO.FileInfo(s); } catch (System.IO.FileNotFoundException e) { // To inform the user and continue is // sufficient for this demonstration. // Your application may require different behavior. Console.WriteLine(e.Message); continue; } Console.WriteLine("{0} : {1}",fi.Name, fi.Directory); } // Change the directory. In this case, first check to see // whether it already exists, and create it if it does not. // If this is not appropriate for your application, you can // handle the System.IO.IOException that will be raised if the // directory cannot be found. if (!System.IO.Directory.Exists(@"C:\Users\Public\TestFolder\")) { System.IO.Directory.CreateDirectory(@"C:\Users\Public\TestFolder\"); } System.IO.Directory.SetCurrentDirectory(@"C:\Users\Public\TestFolder\"); currentDirName = System.IO.Directory.GetCurrentDirectory(); Console.WriteLine(currentDirName); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
private static void FillDriveInfoFromMount(DriveInfo d, GLib.Mount m, string device) { if (m.Volume != null) { // Only get size and format info from physical volumes // (System.IO.DriveInfo throws an exception on network mounts) System.IO.DriveInfo di = new System.IO.DriveInfo (m.Root.Path); d.totalSize = di.TotalSize; d.filesystem = di.DriveFormat; } d.volumeLabel = m.Name; d.rootPath = m.Root.Path; d.device = device; d.driveType = GuessDriveType(m.Root.UriScheme, m.Icon, m.Drive); d.isMounted = true; d.isReady = true; d.hasAudioCdVolume = (m.Root.UriScheme == "cdda"); }
public static long GetFreeSpace() { System.IO.DriveInfo C = new System.IO.DriveInfo("C"); long cAvailableSpace = C.AvailableFreeSpace; return cAvailableSpace; }
/// <summary> /// Popluates the MyComputer node /// </summary> /// <param name="folderItem"></param> /// <param name="parentCollection"></param> /// <param name="helper"></param> protected virtual void FillMyComputer(Raccoom.Win32.ShellItem folderItem, System.Windows.Forms.TreeNodeCollection parentCollection, TreeViewFolderBrowserNodeFactory helper) { _rootCollection = parentCollection; // get wmi logical disk's if we have to System.IO.DriveInfo driveInfo; // folderItem.Expand(true, true, System.IntPtr.Zero); // foreach (Raccoom.Win32.ShellItem fi in folderItem.SubFolders) { // only File System shell objects ? if (!_showAllShellObjects && !fi.IsFileSystem) continue; // if (DriveTypes != DriveTypes.All && fi.IsDisk) { driveInfo = new System.IO.DriveInfo(fi.Path); // switch (driveInfo.DriveType) { case System.IO.DriveType.CDRom: if ((DriveTypes & DriveTypes.CompactDisc) == 0) continue; break; case System.IO.DriveType.Fixed: if ((DriveTypes & DriveTypes.LocalDisk) == 0) continue; break; case System.IO.DriveType.Network: if ((DriveTypes & DriveTypes.NetworkDrive) == 0) continue; break; case System.IO.DriveType.NoRootDirectory: if ((DriveTypes & DriveTypes.NoRootDirectory) == 0) continue; break; case System.IO.DriveType.Ram: if ((DriveTypes & DriveTypes.RAMDisk) == 0) continue; break; case System.IO.DriveType.Removable: if ((DriveTypes & DriveTypes.RemovableDisk) == 0) continue; break; case System.IO.DriveType.Unknown: if ((DriveTypes & DriveTypes.NoRootDirectory) == 0) continue; break; } } // create new node TreeNodePath node = CreateTreeNode(parentCollection, null, fi); } }
private void readDriveInfo() { _info = PropertyHelper.GetPrivateFieldValue<System.IO.DriveInfo[]>(_hardware, "driveInfos").FirstOrDefault(); }
/// <summary> /// Gets the HD information requeried by the server. /// </summary> /// <returns>Returns JObect with the HD info.</returns> public static JObject GetHardDrive() { var harddriveinfo = new JObject(); try { var drivesarray = Environment.GetLogicalDrives(); foreach (var drive in drivesarray) { var di = new System.IO.DriveInfo(drive); if (!di.IsReady) continue; if ((di.DriveType != System.IO.DriveType.Fixed) && (di.DriveType != System.IO.DriveType.Removable)) continue; long tmpHdSize; long tmpHdFree; var name = ((di.VolumeLabel == null) || (di.VolumeLabel.Equals(String.Empty))) ? di.Name : di.VolumeLabel; name = name.Replace("\\", ""); var Size = di.TotalSize.ToString(CultureInfo.InvariantCulture); var InterfaceType = di.DriveFormat; var FreeSpace = di.TotalFreeSpace.ToString(CultureInfo.InvariantCulture); var converted = Int64.TryParse(Size, out tmpHdSize); converted = Int64.TryParse(FreeSpace, out tmpHdFree); if (converted) { tmpHdSize = tmpHdSize / 1024; //Convert to KB from Bytes tmpHdFree = tmpHdFree / 1024; } harddriveinfo["name"] = name; harddriveinfo["file_system"] = InterfaceType; harddriveinfo["file_kb"] = tmpHdSize.ToString(CultureInfo.InvariantCulture); harddriveinfo["free_size_kb"] = tmpHdFree.ToString(CultureInfo.InvariantCulture); } } catch (Exception) { Logger.Log("Error while gathering harddrive info.", LogLevel.Error); } return harddriveinfo; }
private void ProgressProc(object status) { //_logger.LogInformation("tick"); var coll = _scrapes.Values.Where(s => s.IsDownloadInProgress).ToArray(); //_logger.LogInformation("tick " + coll.Count() + " " + coll.FirstOrDefault()?.Id); if(coll.Any()) { var json = JsonConvert.SerializeObject(coll); var jarray = JArray.Parse(json); _hub.Clients.All.broadcastScrapesUpdate(jarray); } var driveInfo = new System.IO.DriveInfo(@"/media/MEDIA"); _hub.Clients.All.broadcastDiskSpaceInfo(BytesToString(driveInfo.AvailableFreeSpace) + " of " + BytesToString(driveInfo.TotalSize)); }
public override void RequestChildNodes(TreeNodePath parent, System.Windows.Forms.TreeViewCancelEventArgs e) { Raccoom.Win32.ShellItem folderItem = ((Raccoom.Win32.ShellItem)parent.Tag); folderItem.Expand(this.ShowFiles, true, System.IntPtr.Zero); // TreeNodePath node = null; System.IO.DriveInfo driveInfo; // foreach (Raccoom.Win32.ShellItem childFolder in folderItem.SubFolders) { if (!_showAllShellObjects && !childFolder.IsFileSystem) continue; // if (DriveTypes != DriveTypes.All && childFolder.IsDisk) { driveInfo = new System.IO.DriveInfo(childFolder.Path); // switch (driveInfo.DriveType) { case System.IO.DriveType.CDRom: if ((DriveTypes & DriveTypes.CompactDisc) == 0) continue; break; case System.IO.DriveType.Fixed: if ((DriveTypes & DriveTypes.LocalDisk) == 0) continue; break; case System.IO.DriveType.Network: if ((DriveTypes & DriveTypes.NetworkDrive) == 0) continue; break; case System.IO.DriveType.NoRootDirectory: if ((DriveTypes & DriveTypes.NoRootDirectory) == 0) continue; break; case System.IO.DriveType.Ram: if ((DriveTypes & DriveTypes.RAMDisk) == 0) continue; break; case System.IO.DriveType.Removable: if ((DriveTypes & DriveTypes.RemovableDisk) == 0) continue; break; case System.IO.DriveType.Unknown: if ((DriveTypes & DriveTypes.NoRootDirectory) == 0) continue; break; } } // node = CreateTreeNode(null, parent, childFolder); } if (!ShowFiles) return; // foreach (Raccoom.Win32.ShellItem fileItem in folderItem.SubFiles) { node = CreateTreeNode(null, parent, fileItem); } }
public static bool Mount(string IsoFile, out string VirtualDrive) { VirtualDrive = string.Empty; if (IsoFile == null) return false; if (IsoFile == string.Empty) return false; if (!_Enabled) return false; if (!System.IO.File.Exists(_Path)) return false; DateTime startTime = DateTime.Now; System.IO.DriveInfo drive = new System.IO.DriveInfo(_Drive); UnMount(); IsoFile = Utils.RemoveTrailingSlash(IsoFile); string strParams = String.Format("-mount {0},\"{1}\"", _DriveNo, IsoFile); Process p = Utils.StartProcess(_Path, strParams, true, true); int timeout = 0; while ((!p.HasExited || !drive.IsReady || !System.IO.Directory.Exists(_Drive + @"\")) && (timeout < 10000)) { System.Threading.Thread.Sleep(100); timeout += 100; } if (timeout >= 10000) { GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ASKYESNO, 0, 0, 0, 0, 0, 0); msg.Param1 = 200093; msg.Param2 = 200094; msg.Param3 = 0; msg.Param4 = 0; msg.Object2 = true; GUIWindowManager.SendMessage(msg); if (msg.Param1 == 1) { while ((!p.HasExited || !drive.IsReady || !System.IO.Directory.Exists(_Drive + @"\")) && (timeout < 60000)) { System.Threading.Thread.Sleep(100); timeout += 100; } if (timeout >= 60000) { Log.Error("Mounting failed after {0}s (second timeout). Check your settings.", (int)(timeout / 1000)); UnMount(); return false; } } else { Log.Error("Mounting failed after {0}s (first timeout). Check your settings.", (int)(timeout / 1000)); UnMount(); return false; } } VirtualDrive = _Drive; _MountedIsoFile = IsoFile; Log.Debug("Mount time: {0}s", String.Format("{0:N}", (DateTime.Now - startTime).TotalSeconds)); return true; }