/// <summary> /// The mouse move event handler. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void c1Chart1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button.Equals(MouseButtons.None)) { int s = -1, p = -1, d = -1; ChartGroup grp = c1Chart1.ChartGroups[0]; if (grp.CoordToDataIndex(e.X, e.Y, CoordinateFocusEnum.XandYCoord, ref s, ref p, ref d)) { if (p >= 0 && d == 0) { if (prePointIndex == -1 && prePointIndex != p) { string ftr; DiskInfo info = arrDiskInfo[p]; if (p < diskCount) { ftr = string.Format("Total Capacity: {0} | VolumnName: {1} | File System: {2}", this.GetSizeString(info.Size, this.Format), info.VolumnName, info.FileSystem); } else { ftr = string.Format("Total Capacity: {0}", this.GetSizeString(info.Size, this.Format)); } c1Chart1.Footer.Text = ftr; prePointIndex = p; } } else { c1Chart1.Footer.Text = "Please move the mouse on each pie to see information in details."; prePointIndex = -1; } } } }
private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { ListViewItem item = listView1.SelectedItems[listView1.SelectedItems.Count - 1]; DiskInfo info = item.Tag as DiskInfo; if (info != null) { ShowDiskInfo(info); } else { FileSystem file = item.Tag as FileSystem; if (file.FileType == FileType.File) { this.label2.Text = "文件:" + file.Name + " 大小:" + Math.Round((double)file.Size / 1024 / 1024, 3) + "MB 最近修改时间:" + file.EditTime; } else { this.label2.Text = "目录:" + file.Name + "最近修改时间:" + file.EditTime; } } } }
public DiskInfo GetDrive(int id) { Disk disk = _Disks.SingleOrDefault(d => d.Id == id); if (disk == null) { return(null); } DriveInfo info = new DriveInfo(disk.Name); DiskInfo drive = new DiskInfo(); drive.Id = id; drive.Name = info.Name; drive.VolumeLable = info.VolumeLabel; drive.IsReady = info.IsReady; drive.DriveType = info.DriveType.ToString(); drive.DriveFormat = info.DriveFormat; drive.TotalSize = info.TotalSize; drive.TotalFreeSpace = info.TotalFreeSpace; drive.AvailableFreeSpace = info.AvailableFreeSpace; return(drive); }
static async Task AdminApiHandler(HttpContext ctx) { string header = "[Komodo.Server.AdminApiHandler] " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " "; _Logging.Info(header + "admin API requested: " + ctx.Request.Method + " " + ctx.Request.Url.RawWithoutQuery); switch (ctx.Request.Method) { case HttpMethod.GET: if (ctx.Request.Url.RawWithoutQuery.Equals("/admin/disks")) { ctx.Response.StatusCode = 200; ctx.Response.ContentType = "application/json"; await ctx.Response.Send(Common.SerializeJson(DiskInfo.GetAllDisks(), true)); return; } break; } _Logging.Warn(header + "unknown endpoint " + ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery); ctx.Response.StatusCode = 400; ctx.Response.ContentType = "application/json"; await ctx.Response.Send(new ErrorResponse(400, "Unknown endpoint.", null, null).ToJson(true)); return; }
/// <summary> /// 获取磁盘详情 /// </summary> /// <param name="driveInfos"></param> /// <returns></returns> public static DiskInfo[] ConvertToDiskInfo(DriveInfo[] driveInfos) { DiskInfo[] diskInfos = new DiskInfo[driveInfos.Length]; for (int i = 0; i < driveInfos.Length; i++) { if (driveInfos[i].IsReady) { diskInfos[i] = new DiskInfo() { Name = driveInfos[i].Name, TotalSize = driveInfos[i].TotalSize, AvailableFreeSpace = driveInfos[i].AvailableFreeSpace, TotalFreeSpace = driveInfos[i].TotalFreeSpace, DriveFormat = driveInfos[i].DriveFormat, DriveType = driveInfos[i].DriveType.ToString(), IsReady = driveInfos[i].IsReady, RootDirectory = driveInfos[i].RootDirectory.Name, VolumeLabel = driveInfos[i].VolumeLabel }; } else { diskInfos[i] = new DiskInfo() { Name = driveInfos[i].Name }; } } return(diskInfos); }
public TestFile(string drivePath, long testAreaSizeBytes) { Path = DiskInfo.GetTempFilePath(drivePath); TestAreaSizeBytes = testAreaSizeBytes; WriteStream = new FileStream(Path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, _buffer, FileOptions.WriteThrough); ReadStream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, _buffer, (FileOptions)0x20000000); }
/// <summary> /// Поток копирования каталога /// </summary> /// <param name="copyInf"></param> private void CopyStructureThread(object copyInf) { var copyInfo = (CopyInfo)copyInf; var neededPath = copyInfo.NeededPath; string drive = "\\\\.\\" + copyInfo.SelectedDrive; drive = drive.Remove(drive.Length - 1, 1); //анализ выбранного диска DiskInfo diskInfoHandle = new DiskInfo(drive); //если выбранный диск не является NTFS if (diskInfoHandle.NotNTFSFlag) { MessageBox.Show("Данный раздел не является томом NTFS!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { var np = neededPath.ToCharArray(); np[0] = drive[4]; string toPath = new string(np); //скопировать каталоги copyInfo.CopyDirs(neededPath, toPath); MessageBox.Show("Каталог успешно скопирован.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
static IEnumerable <DiskInfo> GetPhysicalDiskList() { var drives = new List <DiskInfo>(); var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject mobj in searcher.Get()) { var di = new DiskInfo(); try { di.FileName = mobj["Name"].ToString(); di.Model = mobj["Model"].ToString(); di.PartitionCount = mobj["Partitions"].ToString(); di.BytesPerSector = mobj["BytesPerSector"].ToString(); di.TotalSectors = mobj["TotalSectors"].ToString(); di.TotalSize = mobj["Size"].ToString(); di.Description = mobj["Description"].ToString(); di.InterfaceType = mobj["InterfaceType"].ToString(); di.MediaType = mobj["MediaType"].ToString(); di.SerialNumber = mobj["SerialNumber"].ToString(); } catch { } drives.Add(di); } return(drives.ToArray()); }
/// <summary> /// Reads Config file. /// </summary> /// <remarks>True if completed</remarks> internal async Task <bool> ReadAsync(DiskInfo info) { if (info == null) { throw new ArgumentNullException(nameof(info)); } AssociatedDisk = info; var configPath = ComposeConfigPath(); if (!File.Exists(configPath)) { return(false); } try { using (var sr = new StreamReader(configPath, Encoding.ASCII)) { Import(await sr.ReadToEndAsync()); return(true); } } catch (Exception ex) { Debug.WriteLine($"Failed to read config file.\r\n{ex}"); return(false); } }
public DiskAPI() { Sync = TaskScheduler.FromCurrentSynchronizationContext(); // Never mind... Token = SettingsService.Instance.CurrentUserData.Token; Task.Run(async() => Info = await GetDiskInfo()); }
//[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")] #endregion public void ntfsread(IProgress <int> progress, IProgress <string> fase, bool update) { string[] drivetoscan = DiskInfo.listDrive().ToArray(); createDB(update); SharedVar.listScore = getAllIndexProcess(); int i = 1; foreach (string drive in drivetoscan) { progress?.Report(i * 100 / drivetoscan.Length - 1); fase?.Report("Indexing Drive " + drive + ":\\ in progress. Please wait a few seconds."); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); DriveInfo driveToAnalyze = new DriveInfo(drive); NtfsReader ntfsReader = new NtfsReader(driveToAnalyze, RetrieveMode.All); IEnumerable <INode> nodes = ntfsReader.GetNodes(driveToAnalyze.Name) .Where(n => (n.Attributes & (Attributes.Hidden | Attributes.System | Attributes.Temporary | Attributes.Device | Attributes.Directory | Attributes.Offline | Attributes.ReparsePoint | Attributes.SparseFile)) == 0) .OrderByDescending(n => n.Size); ntfsReader.Dispose(); InsertNodes(nodes, driveToAnalyze, update); i++; } }
private void listView1_DoubleClick(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { ListViewItem item = listView1.SelectedItems[listView1.SelectedItems.Count - 1]; string DirName = ""; FileSystem dirinfo = item.Tag as FileSystem; if (dirinfo != null) { if (dirinfo.FileType == FileType.Dir) { DirName = dirinfo.FullName; } else { if (MessageBox.Show("是否下载文件:" + dirinfo.Name + "?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { FileSystem downFile = (this.listView1.SelectedItems[this.listView1.SelectedItems.Count - 1].Tag as FileSystem); if (downFile != null) { Down down = new Down() { FullName = downFile.FullName }; SocketManager.Send(BufferFormatV2.FormatFCA(down, Deflate.Compress)); } } return; } } else { DiskInfo info = item.Tag as DiskInfo; if (info != null) { DirName = info.Name; } } Dir tmp = new Dir() { DirName = DirName, FileSystemList = new List <FileSystem>(), IsSuccess = false, Msg = "" }; SocketManager.Send(BufferFormatV2.FormatFCA(tmp, Deflate.Compress)); } }
/// <summary> /// 获取每簇的字节 /// </summary> /// <param name="file">指定文件</param> /// <returns></returns> public static long GetClusterSize(FileInfo file) { long clusterSize = 0; DiskInfo diskInfo = new DiskInfo(); diskInfo = GetDiskInfo(file.Directory.Root.FullName); clusterSize = (diskInfo.BytesPerSector * diskInfo.SectorsPerCluster); return clusterSize; }
public DiskInfoModel(DiskInfo info) : this() { VolumeName = info.VolumeName; Name = info.Name; SizeInGB = info.SizeInGB; FreeSpaceInGB = info.FreeSpaceInGB; PercentFree = info.PercentFree; }
/// <summary> /// 获取每簇的字节 /// </summary> /// <param name="dir">指定目录</param> /// <returns></returns> public static long GetClusterSize(DirectoryInfo dir) { long clusterSize = 0; DiskInfo diskInfo = new DiskInfo(); diskInfo = GetDiskInfo(dir.Root.FullName); clusterSize = (diskInfo.BytesPerSector * diskInfo.SectorsPerCluster); return(clusterSize); }
public static async Task HttpGetDisks(RequestMetadata md) { List <DiskInfo> ret = DiskInfo.GetAllDisks(); md.Http.Response.StatusCode = 200; md.Http.Response.ContentType = "application/json"; await md.Http.Response.Send(Common.SerializeJson(ret, true)); return; }
//Disk info counter private void diskcount() { diskCLabel1.Text = "Drive: " + DiskInfo.diskName; diskCLabel2.Text = "Total Disk Space = " + DiskInfo.totalDiskSpaceInGb + " GB"; diskCLabel3.Text = "Total Free Disk Space = " + DiskInfo.avaliableDiskSpace + " GB"; diskProgressBar.Maximum = Convert.ToInt32(DiskInfo.totalDiskSpaceInGb); diskProgressBar.Text = Convert.ToString(DiskInfo.DiskFreeSpace()) + " GB"; diskProgressBar.Value = DiskInfo.DiskFreeSpace(); }
private void lblAutoAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { SSHConnectionDetails sshConnection = sshConnectionDetails.Clone(); sshConnection.ComputerName = ApplyConfigVarsOnField(sshConnection.ComputerName); sshConnection.UserName = ApplyConfigVarsOnField(sshConnection.UserName); sshConnection.Password = ApplyConfigVarsOnField(sshConnection.Password); sshConnection.PrivateKeyFile = ApplyConfigVarsOnField(sshConnection.PrivateKeyFile); sshConnection.PassPhrase = ApplyConfigVarsOnField(sshConnection.PassPhrase); sshConnection.ConnectionName = ApplyConfigVarsOnField(sshConnection.ConnectionName); sshConnection.ConnectionString = ApplyConfigVarsOnField(sshConnection.ConnectionString); if (lvwFileSystems.Items.Count > 0 && (MessageBox.Show("Clear all existing entries?", "Clear", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)) { return; } else { lvwFileSystems.Items.Clear(); lvwFileSystems.Items.Add(new ListViewItem("Querying " + sshConnection.ComputerName + "...")); Application.DoEvents(); } Renci.SshNet.SshClient sshClient = SshClientTools.GetSSHConnection(sshConnection); if (sshClient.IsConnected) { lvwFileSystems.Items.Clear(); foreach (DiskInfo di in DiskInfo.FromDfTk(sshClient)) { NIXDiskSpaceSubEntry dsse = new NIXDiskSpaceSubEntry() { FileSystemName = di.Name, WarningValue = (double)warningNumericUpDown.Value, ErrorValue = (double)errorNumericUpDown.Value }; ListViewItem lvi = new ListViewItem() { Text = dsse.FileSystemName }; lvi.SubItems.Add(dsse.WarningValue.ToString()); lvi.SubItems.Add(dsse.ErrorValue.ToString()); lvi.Tag = dsse; lvwFileSystems.Items.Add(lvi); } } else { lvwFileSystems.Items.Clear(); MessageBox.Show("Could not connect to computer!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
static void Main(string[] args) { if (0 == args.Length) { string executableName = AssemblyHelper.ExecutableName; string applicationName = Path.GetFileNameWithoutExtension(executableName); Console.WriteLine("{0} [UNC-path|Drive]...", applicationName); Console.WriteLine(@"Example: {0} C: \\{1}\Users", applicationName, Environment.MachineName); } else { string header = string.Empty; StringBuilder result = new StringBuilder(); foreach (string arg in args) { try { DiskFreeSpaceEx diskFreeSpaceEx = DiskInfo.GetDiskFreeSpaceEx(arg); VolumeInformation volumeInformation = DiskInfo.GetVolumeInformation(arg); var values = new { diskFreeSpaceEx.DirectoryName, diskFreeSpaceEx.FreeBytesAvailable, diskFreeSpaceEx.TotalNumberOfBytes, diskFreeSpaceEx.TotalNumberOfFreeBytes, volumeInformation.VolumeSerialNumber, volumeInformation.MaximumComponentLength, volumeInformation.FileSystemFlags, volumeInformation.FileSystemName, volumeInformation.VolumeName, }; IList <string> valueStrings = Reflector.GetValueStrings(values); const string separator = ";"; string line = string.Join(separator, valueStrings); result.AppendLine(line); IList <string> names = Reflector.GetNames(values); header = string.Join(separator, names); } catch (Exception ex) { Console.WriteLine("Exception processing '{0}': {1}", arg, ex); } } if (result.Length > 0) { Console.WriteLine(header); Console.Write(result); } } }
public ActionResult <DiskInfo> GetDriveInfo(int id) { DiskInfo drive = _diskService.GetDrive(id); if (drive == null) { return(NotFound()); } return(drive); }
public DiskStream(string diskID, FileAccess desiredAccess) { this.diskID = diskID; this.diskInfo = new DiskInfo(diskID); this.desiredAccess = desiredAccess; // if desiredAccess is Write or Read/Write // find volumes on this disk // lock the volumes using FSCTL_LOCK_VOLUME // unlock the volumes on Close() or in destructor this.fileHandle = this.openFile(diskID, desiredAccess); }
/// <summary> /// Gather all informations about the server and the program /// </summary> /// <param name="servicename">Name of the service from where this is collected</param> /// <param name="programVersion">Versionname of the program/service</param> public void CollectData(string servicename, string programVersion) { this.Servername = Process.GetCurrentProcess().MachineName; this.Disks = DiskInfo.CollectData().ToArray(); this.Uptime = DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime); this.Cpu = CpuInfo.CollectData(this.Uptime); this.Ram = RamInfo.CollectData(); this.Timestamp = DateTime.Now; this.Servicename = servicename; this.ServiceVersion = programVersion; }
public static DiskInfo GetDiskInfo(string rootPathName) { DiskInfo diskInfo = new DiskInfo(); int sectorsPerCluster = 0, bytesPerSector = 0, numberOfFreeClusters = 0, totalNumberOfClusters = 0; GetDiskFreeSpace(rootPathName, ref sectorsPerCluster, ref bytesPerSector, ref numberOfFreeClusters, ref totalNumberOfClusters); //每簇的扇区数 diskInfo.SectorsPerCluster = sectorsPerCluster; //每扇区字节 diskInfo.BytesPerSector = bytesPerSector; return(diskInfo); }
private void bgwSpaceCounter_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try { //e.Result = DiskInfo.GetDirSizeByMonteCarlo((string)e.Argument); e.Result = DiskInfo.GetDirSizeFast((string)e.Argument); } catch (Exception) { e.Result = 0; } }
public Disk(DiskInfo diskProps) { FriendlyName = diskProps.FriendlyName; Number = diskProps.Number; Size = diskProps.Size; AllocatedSize = diskProps.AllocatedSize; FriendlyName = diskProps.FriendlyName; IsSystem = diskProps.IsSystem; IsBoot = diskProps.IsBoot; IsReadOnly = diskProps.IsReadOnly; IsOffline = diskProps.IsOffline; UniqueId = diskProps.UniqueId; }
//Form loading Setup private void Monitoring_Load(object sender, EventArgs e) { //Setup the RAM info ramProgressBar.Maximum = RamInfo.TotalRamInMB(); ramAmountLabel.Text = "Amount of RAM = " + Convert.ToString(Math.Round(RamInfo.TotalRamInMB() / MbInGB, 1)) + "GB"; //Setup the Computer name for counters cpuCounter.MachineName = compName; sysUpTimeCounter.MachineName = compName; DiskInfo.CheckDiskC(); //cpuTemperatureTimer.Start(); }
public List <DiskInfoState> GetDiskInfos() { List <DiskInfoState> fileSystemEntries = new List <DiskInfoState>(); Renci.SshNet.SshClient sshClient = SSHConnection.GetConnection(); //First see if ANY subentry is for all bool addAll = (from LinuxDiskSpaceSubEntry d in SubItems where d.FileSystemName == "*" select d).Count() > 0; if (addAll) { LinuxDiskSpaceSubEntry alertDef = (from LinuxDiskSpaceSubEntry d in SubItems where d.FileSystemName == "*" select d).FirstOrDefault(); foreach (Linux.DiskInfo di in DiskInfo.FromDfTk(sshClient)) { DiskInfoState dis = new DiskInfoState() { FileSystemInfo = di, State = CollectorState.NotAvailable, AlertDefinition = alertDef }; fileSystemEntries.Add(dis); } } else { foreach (Linux.DiskInfo di in DiskInfo.FromDfTk(sshClient)) { LinuxDiskSpaceSubEntry alertDef = (from LinuxDiskSpaceSubEntry d in SubItems where d.FileSystemName.ToLower() == di.Name.ToLower() select d).FirstOrDefault(); if (alertDef != null) { if (!fileSystemEntries.Any(f => f.FileSystemInfo.Name.ToLower() == di.Name.ToLower())) { DiskInfoState dis = new DiskInfoState() { FileSystemInfo = di, State = CollectorState.NotAvailable, AlertDefinition = alertDef }; fileSystemEntries.Add(dis); } } } } SSHConnection.CloseConnection(); return(fileSystemEntries); }
private void AnalyzeFileGroupThread(object filesobj) { var files = (List <string>)filesobj; var mftViewTable = new List <TableView>(); if (files.Count == 0) { MessageBox.Show("Вы не выбрали ни одного файла!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { foreach (var file in files) { //разбиваем путьк файлу на каталоги var catalogs = file.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); DiskInfo diskHandle = new DiskInfo(catalogs[0]); if (!diskHandle.NotNTFSFlag) { // 5 запись является корневым каталогом, обращаемся к ней при старте поиска int nextRecord = 5; // в объявленной переменной хранится текущий каталог MFTHandle root; for (int i = 1; i < catalogs.Length; i++) { // считывание следующей записи MFT root = diskHandle.GetMftRecord(nextRecord); // поиск номера записи МФТ следующего каталога nextRecord = DiskInfo.FoundSubdir(root, catalogs[i]); } MFTHandle detectedFile = diskHandle.GetMftRecord(nextRecord); mftViewTable.Add(new TableView(detectedFile)); foreach (var index in detectedFile.Indexes) { mftViewTable.Add(new TableView(diskHandle.GetMftRecord((int)index.IndexedFile))); } MessageBox.Show("Группа файлов успешно проанализирована", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show($"Файл {file} находится на диске, не являющимся томом NTFS", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Error); } } AnalyzeDataView.DataSource = null; // вывод данных в таблицу на форме AnalyzeDataView.DataSource = mftViewTable; } }
public DiskInfo GetInfo() { DriveInfo hostingDrive = new DriveInfo("D:\\"); var totalSpace = hostingDrive.TotalSize / 1048576; var freeSpace = hostingDrive.TotalFreeSpace / 1048576; var UsedSpace = totalSpace - freeSpace; var result = new DiskInfo(); result.Total = totalSpace; result.Free = freeSpace; result.Used = UsedSpace; return(result); }
private void bgwSpaceCounter_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { // First, handle the case where an exception was thrown. if (e.Error != null) { Program.ShowMessageBox(e.Error.Message); } else { // Finally, handle the case where the operation succeeded. long usedByApp = Convert.ToInt64(e.Result); lblUsedBytes.Text = usedByApp.ToString("###,###,###,###,###,##0") + " bytes"; lblUsedGbytes.Text = DiskInfo.ConvertBytes(usedByApp); isSizeCounted = true; } }
/// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, DiskInfo obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); if (obj.Capacity != null) { writer.WriteProperty(obj.Capacity, "Capacity", JsonWriterExtensions.WriteStringValue); } if (obj.AvailableSpace != null) { writer.WriteProperty(obj.AvailableSpace, "AvailableSpace", JsonWriterExtensions.WriteStringValue); } writer.WriteEndObject(); }
/// <summary> /// /// </summary> /// <param name="rootPathName"></param> /// <returns></returns> public static DiskInfo GetDiskInfo(string rootPathName) { DiskInfo diskInfo = new DiskInfo(); int sectorsPerCluster = 0, bytesPerSector = 0, numberOfFreeClusters = 0, totalNumberOfClusters = 0; GetDiskFreeSpace(rootPathName, ref sectorsPerCluster, ref bytesPerSector, ref numberOfFreeClusters, ref totalNumberOfClusters); //每簇的扇区数 diskInfo.SectorsPerCluster = sectorsPerCluster; //每扇区字节 diskInfo.BytesPerSector = bytesPerSector; return diskInfo; }
/// <summary> /// 获取本机磁盘信息 /// ,磁盘大小的单位为MB /// </summary> /// <returns></returns> public List<DiskInfo> GetDiskInfo() { List<DiskInfo> lstDisk = new List<DiskInfo>(); string ip = ""; IPHostEntry myHost = new IPHostEntry(); myHost = Dns.GetHostEntry(Dns.GetHostName()); ip = myHost.AddressList[0].ToString(); System.Management.ObjectQuery Query = new System.Management.ObjectQuery("select FreeSpace ,Size ,Name from Win32_LogicalDisk where DriveType=3"); ManagementObjectCollection ReturnCollection = new ManagementObjectSearcher(Query).Get(); foreach (ManagementObject Return in ReturnCollection) { DiskInfo diskObj = new DiskInfo(); diskObj.IP = ip; diskObj.DiskName = Return["Name"].ToString(); //磁盘名称 diskObj.ActualSpace = Convert.ToInt32(Convert.ToInt64(Return["Size"].ToString()) / Constants .SIZE_MB ); //实际空间 diskObj.RemainSpace = Convert.ToInt32(Convert.ToInt64(Return["FreeSpace"].ToString()) / Constants .SIZE_MB); //剩余空间 diskObj.UsedSpace = diskObj.ActualSpace - diskObj.RemainSpace; //已使用空间 diskObj.AllowSpace = diskObj.ActualSpace - 2048;//允许存储空间 lstDisk.Add(diskObj); } return lstDisk; }