Obtenir de l’espace disque libre

Étant donné chacune des entrées ci-dessous, j’aimerais obtenir de l’espace libre à cet endroit. Quelque chose comme

long GetFreeSpace(ssortingng path) 

Consortingbutions:

 c: c:\ c:\temp \\server \\server\C\storage 

cela fonctionne pour moi …

 using System.IO; private long GetTotalFreeSpace(ssortingng driveName) { foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (drive.IsReady && drive.Name == driveName) { return drive.TotalFreeSpace; } } return -1; } 

bonne chance!

DriveInfo va vous aider avec certains de ces éléments (mais cela ne fonctionne pas avec les chemins UNC), mais je pense vraiment que vous devrez utiliser GetDiskFreeSpaceEx . Vous pouvez probablement obtenir des fonctionnalités avec WMI. GetDiskFreeSpaceEx ressemble à votre meilleur pari.

Les chances sont que vous devrez probablement nettoyer vos chemins pour le faire fonctionner correctement.

GetDiskFreeSpaceEx de code de travail utilisant GetDiskFreeSpaceEx depuis le lien par RichardOD.

 // Pinvoke for API function [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetDiskFreeSpaceEx(ssortingng lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); public static bool DriveFreeBytes(ssortingng folderName, out ulong freespace) { freespace = 0; if (ssortingng.IsNullOrEmpty(folderName)) { throw new ArgumentNullException("folderName"); } if (!folderName.EndsWith("\\")) { folderName += '\\'; } ulong free = 0, dummy1 = 0, dummy2 = 0; if (GetDiskFreeSpaceEx(folderName, out free, out dummy1, out dummy2)) { freespace = free; return true; } else { return false; } } 
 using System; using System.IO; class Test { public static void Main() { DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}", d.Name); Console.WriteLine(" Drive type: {0}", d.DriveType); if (d.IsReady == true) { Console.WriteLine(" Volume label: {0}", d.VolumeLabel); Console.WriteLine(" File system: {0}", d.DriveFormat); Console.WriteLine( " Available space to current user:{0, 15} bytes", d.AvailableFreeSpace); Console.WriteLine( " Total available space: {0, 15} bytes", d.TotalFreeSpace); Console.WriteLine( " Total size of drive: {0, 15} bytes ", d.TotalSize); } } } } /* This code produces output similar to the following: Drive A:\ Drive type: Removable Drive C:\ Drive type: Fixed Volume label: File system: FAT32 Available space to current user: 4770430976 bytes Total available space: 4770430976 bytes Total size of drive: 10731683840 bytes Drive D:\ Drive type: Fixed Volume label: File system: NTFS Available space to current user: 15114977280 bytes Total available space: 15114977280 bytes Total size of drive: 25958948864 bytes Drive E:\ Drive type: CDRom The actual output of this code will vary based on machine and the permissions granted to the user executing it. */ 

non testé:

 using System; using System.Management; ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid="c:""); disk.Get(); Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes"); Console.WriteLine("Logical Disk FreeSpace = " + disk["FreeSpace"] + " bytes"); 

Btw quel est le résultat de l’espace disque libre sur c: \ temp? vous aurez l’espace libre de c: \

voir cet article !

  1. identifier le chemin d’access UNC ou local en recherchant l’index de “:”

  2. si c’est UNC PATH vous cam cam UNC chemin

  3. code pour exécuter le nom du lecteur est le nom du lecteur mappé .

     using System.IO; private long GetTotalFreeSpace(ssortingng driveName) { foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (drive.IsReady && drive.Name == driveName) { return drive.TotalFreeSpace; } } return -1; } 
  4. unmap après que vous ayez fait

Je cherchais la taille en Go, j’ai donc amélioré le code de Superman ci-dessus avec les modifications suivantes:

 public double GetTotalHDDSize(ssortingng driveName) { foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (drive.IsReady && drive.Name == driveName) { return drive.TotalSize / (1024 * 1024 * 1024); } } return -1; } 

Je voulais une méthode similaire pour mon projet, mais dans mon cas, les chemins d’entrée étaient soit des volumes de disques locaux, soit des volumes de stockage en cluster (CSV). La classe DriveInfo ne fonctionnait donc pas pour moi. Les CSV ont un sharepoint assembly sous un autre lecteur, généralement C: \ ClusterStorage \ Volume *. Notez que C: sera un volume différent de C: \ ClusterStorage \ Volume1

C’est ce que j’ai finalement trouvé:

  public static ulong GetFreeSpaceOfPathInBytes(ssortingng path) { if ((new Uri(path)).IsUnc) { throw new NotImplementedException("Cannot find free space for UNC path " + path); } ulong freeSpace = 0; int prevVolumeNameLength = 0; foreach (ManagementObject volume in new ManagementObjectSearcher("Select * from Win32_Volume").Get()) { if (UInt32.Parse(volume["DriveType"].ToSsortingng()) > 1 && // Is Volume monuted on host volume["Name"] != null && // Volume has a root directory path.StartsWith(volume["Name"].ToSsortingng(), SsortingngComparison.OrdinalIgnoreCase) // Required Path is under Volume's root directory ) { // If multiple volumes have their root directory matching the required path, // one with most nested (longest) Volume Name is given preference. // Case: CSV volumes monuted under other drive volumes. int currVolumeNameLength = volume["Name"].ToSsortingng().Length; if ((prevVolumeNameLength == 0 || currVolumeNameLength > prevVolumeNameLength) && volume["FreeSpace"] != null ) { freeSpace = ulong.Parse(volume["FreeSpace"].ToSsortingng()); prevVolumeNameLength = volume["Name"].ToSsortingng().Length; } } } if (prevVolumeNameLength > 0) { return freeSpace; } throw new Exception("Could not find Volume Information for path " + path); } 

Comme cette réponse et @RichardOD ont suggéré, vous devriez faire comme ceci:

 [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetDiskFreeSpaceEx(ssortingng lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); ulong FreeBytesAvailable; ulong TotalNumberOfBytes; ulong TotalNumberOfFreeBytes; bool success = GetDiskFreeSpaceEx(@"\\mycomputer\myfolder", out FreeBytesAvailable, out TotalNumberOfBytes, out TotalNumberOfFreeBytes); if(!success) throw new System.ComponentModel.Win32Exception(); Console.WriteLine("Free Bytes Available: {0,15:D}", FreeBytesAvailable); Console.WriteLine("Total Number Of Bytes: {0,15:D}", TotalNumberOfBytes); Console.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes); 

Check it out (Ceci est une solution de travail pour moi)

 public long AvailableFreeSpace() { long longAvailableFreeSpace = 0; try{ DriveInfo[] arrayOfDrives = DriveInfo.GetDrives(); foreach (var d in arrayOfDrives) { Console.WriteLine("Drive {0}", d.Name); Console.WriteLine(" Drive type: {0}", d.DriveType); if (d.IsReady == true && d.Name == "/data") { Console.WriteLine("Volume label: {0}", d.VolumeLabel); Console.WriteLine("File system: {0}", d.DriveFormat); Console.WriteLine("AvailableFreeSpace for current user:{0, 15} bytes",d.AvailableFreeSpace); Console.WriteLine("TotalFreeSpace {0, 15} bytes",d.TotalFreeSpace); Console.WriteLine("Total size of drive: {0, 15} bytes \n",d.TotalSize); } longAvailableFreeSpaceInMB = d.TotalFreeSpace; } } catch(Exception ex){ ServiceLocator.GetInsightsProvider()?.LogError(ex); } return longAvailableFreeSpace; } 

J’ai eu le même problème et j’ai vu la mangue de waruna donner la meilleure réponse. Cependant, tout écrire sur la console n’est pas ce que vous pourriez souhaiter. Pour obtenir une chaîne de caractères, utilisez ce qui suit

Première étape: déclarer les valeurs au début

  //drive 1 public static ssortingng drivename = ""; public static ssortingng drivetype = ""; public static ssortingng drivevolumelabel = ""; public static ssortingng drivefilesystem = ""; public static ssortingng driveuseravailablespace = ""; public static ssortingng driveavailablespace = ""; public static ssortingng drivetotalspace = ""; //drive 2 public static ssortingng drivename2 = ""; public static ssortingng drivetype2 = ""; public static ssortingng drivevolumelabel2 = ""; public static ssortingng drivefilesystem2 = ""; public static ssortingng driveuseravailablespace2 = ""; public static ssortingng driveavailablespace2 = ""; public static ssortingng drivetotalspace2 = ""; //drive 3 public static ssortingng drivename3 = ""; public static ssortingng drivetype3 = ""; public static ssortingng drivevolumelabel3 = ""; public static ssortingng drivefilesystem3 = ""; public static ssortingng driveuseravailablespace3 = ""; public static ssortingng driveavailablespace3 = ""; public static ssortingng drivetotalspace3 = ""; 

Etape 2: code actuel

  DriveInfo[] allDrives = DriveInfo.GetDrives(); int drive = 1; foreach (DriveInfo d in allDrives) { if (drive == 1) { drivename = Ssortingng.Format("Drive {0}", d.Name); drivetype = Ssortingng.Format("Drive type: {0}", d.DriveType); if (d.IsReady == true) { drivevolumelabel = Ssortingng.Format("Volume label: {0}", d.VolumeLabel); drivefilesystem = Ssortingng.Format("File system: {0}", d.DriveFormat); driveuseravailablespace = Ssortingng.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace); driveavailablespace = Ssortingng.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace); drivetotalspace = Ssortingng.Format("Total size of drive:{0, 15} bytes ", d.TotalSize); } drive = 2; } else if (drive == 2) { drivename2 = Ssortingng.Format("Drive {0}", d.Name); drivetype2 = Ssortingng.Format("Drive type: {0}", d.DriveType); if (d.IsReady == true) { drivevolumelabel2 = Ssortingng.Format("Volume label: {0}", d.VolumeLabel); drivefilesystem2 = Ssortingng.Format("File system: {0}", d.DriveFormat); driveuseravailablespace2 = Ssortingng.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace); driveavailablespace2 = Ssortingng.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace); drivetotalspace2 = Ssortingng.Format("Total size of drive:{0, 15} bytes ", d.TotalSize); } drive = 3; } else if (drive == 3) { drivename3 = Ssortingng.Format("Drive {0}", d.Name); drivetype3 = Ssortingng.Format("Drive type: {0}", d.DriveType); if (d.IsReady == true) { drivevolumelabel3 = Ssortingng.Format("Volume label: {0}", d.VolumeLabel); drivefilesystem3 = Ssortingng.Format("File system: {0}", d.DriveFormat); driveuseravailablespace3 = Ssortingng.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace); driveavailablespace3 = Ssortingng.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace); drivetotalspace3 = Ssortingng.Format("Total size of drive:{0, 15} bytes ", d.TotalSize); } drive = 4; } if (drive == 4) { drive = 1; } } //part 2: possible debug - displays in output //drive 1 Console.WriteLine(drivename); Console.WriteLine(drivetype); Console.WriteLine(drivevolumelabel); Console.WriteLine(drivefilesystem); Console.WriteLine(driveuseravailablespace); Console.WriteLine(driveavailablespace); Console.WriteLine(drivetotalspace); //drive 2 Console.WriteLine(drivename2); Console.WriteLine(drivetype2); Console.WriteLine(drivevolumelabel2); Console.WriteLine(drivefilesystem2); Console.WriteLine(driveuseravailablespace2); Console.WriteLine(driveavailablespace2); Console.WriteLine(drivetotalspace2); //drive 3 Console.WriteLine(drivename3); Console.WriteLine(drivetype3); Console.WriteLine(drivevolumelabel3); Console.WriteLine(drivefilesystem3); Console.WriteLine(driveuseravailablespace3); Console.WriteLine(driveavailablespace3); Console.WriteLine(drivetotalspace3); 

Je tiens à noter que vous pouvez simplement faire tout le code de commentaire des lignes d’écriture de la console, mais j’ai pensé que ce serait bien de le tester. Si vous affichez tout cela les uns après les autres, vous obtenez la même liste que waruna majuna

Lecteur C: \ Type de lecteur: Libellé Volume: Système de fichiers: NTFS Espace disponible pour l’utilisateur actuel: 134880153600 octets Espace total disponible: 134880153600 octets Taille totale du lecteur: 499554185216 octets

Drive D: \ Type de lecteur: CDRom

Lecteur H: \ Type de lecteur: Fixe Libellé du volume: Disque dur Système de fichiers: NTFS Espace disponible pour l’utilisateur actuel: 2000010817536 octets Espace total disponible: 2000010817536 octets Taille totale du lecteur: 2000263573504 octets

Cependant, vous pouvez maintenant accéder à toutes les informations en vrac sur les chaînes