C # Get the size of folders and files and how they occupy space

Source: Internet
Author: User

This paper introduces in detail the method of using C # to calculate the disk space occupied by this path according to the path.

There is a lot of information on the Internet to get the size of the folder/file. There is very little complete code for the space footprint. The complete code for this function is described here for your reference.

First, the difference between the folder/file size and the occupied space.

This is hard disk partition format about size is the actual size of the file, and occupy space is the actual space of the hard disk in the FAT32 format, for example, the basic storage unit of the hard disk is a cluster, in FAT32 a cluster is 4KB then, that is, even if the file only 1 bytes, on the hard disk to occupy 4KB of space If the file is 4KB 1 bytes, it takes up 8KB of space, and so on.

Conclusion: The size is the actual size of the file, while occupying space is the actual space of the hard disk.

So here's the problem. How many bytes does it take to get a native cluster?

You can first get information about the disk through the Windows API.

//call the Windows API to get disk free space//Import Library[DllImport ("Kernel32.dll", CharSet =CharSet.Auto)]Static extern BOOLGetDiskFreeSpace ([MarshalAs (UNMANAGEDTYPE.LPTSTR)]stringRootpathname,ref intSectorsPerCluster,ref intBytesPerSector,ref intNumberoffreeclusters,ref intTotalnumbeofclusters);

Here is the specific code:

/// <summary>///gets the size of the specified path/// </summary>/// <param name= "Dirpath" >Path</param>/// <returns></returns> Public Static LongGetdirectorylength (stringDirpath) {LongLen =0;//determine if the path exists (is a folder)if(!directory.exists (Dirpath)) {//querying the size of a fileLen =FileSize (Dirpath);}Else{//define a DirectoryInfo objectDirectoryInfo di =NewDirectoryInfo (dirpath);//get the size of all files in the Di directory through the GetFiles methodforeach(FileInfo fiinchdi. GetFiles ()) {Len+=fi. Length;}//get all the folders in Di and coexist in a new object array for recursiondirectoryinfo[] dis =di. GetDirectories ();if(Dis. Length >0){ for(inti =0; i < Dis. Length; i++) {len+=getdirectorylength (Dis[i]. FullName); }}}returnLen;} /// <summary>///Gets the space occupied by the specified path/// </summary>/// <param name= "Dirpath" >Path</param>/// <returns></returns> Public Static LongGetdirectoryspace (stringDirpath) {//return valueLongLen =0;//determine if the path exists (is a folder)if(!directory.exists (Dirpath)) {//if it is a file, call theLen =Filespace (Dirpath);}Else{//define a DirectoryInfo objectDirectoryInfo di =NewDirectoryInfo (dirpath);//the cluster value of this machineLongClustersize =getclustersize (di);//traverse files in the directory to get total space occupiedforeach(FileInfo fiinchdi. GetFiles ()) {//The file size divided by the cluster, the remainder is not 0if(FI. Length% clustersize! =0){decimalres = fi. Length/clustersize;//divide the file size by the cluster and take the integer plus 1. The value of the cluster for the fileintCLU = Convert.ToInt32 (math.ceiling (res)) +1;Longresult = Clustersize *Clu;len+=result;}Else{//Yu Jo is 0, space is equal to file sizeLen + =fi. Length;}}//get all the folders in Di and coexist in a new object array for recursiondirectoryinfo[] dis =di. GetDirectories ();if(Dis. Length >0){ for(inti =0; i < Dis. Length; i++) {len+=getdirectoryspace (Dis[i]. FullName); }}}returnLen;} //The file size corresponding to the given path Public Static LongFileSize (stringFilePath) {//defines a FileInfo object that is associated with the file pointed to by FilePath to get its sizeFileInfo FileInfo =NewFileInfo (filePath);returnFileinfo.length;} //The files in the given path occupy space Public Static LongFilespace (stringFilePath) {Longtemp =0;//defines a FileInfo object that is associated with the file pointed to by FilePath to get its sizeFileInfo FileInfo =NewFileInfo (filePath);LongClustersize =getclustersize (fileInfo);if(fileinfo.length% clustersize! =0){decimalres = fileinfo.length/clustersize;intCLU = Convert.ToInt32 (math.ceiling (res)) +1; Temp= Clustersize *CLU;}Else{returnfileinfo.length;}returntemp;}  Public StaticDiskInfo Getdiskinfo (stringrootpathname) {DiskInfo DiskInfo=NewDiskInfo ();intSectorsPerCluster =0, BytesPerSector =0, numberoffreeclusters =0, totalnumberofclusters =0; GetDiskFreeSpace (Rootpathname,refSectorsPerCluster,refBytesPerSector,refNumberoffreeclusters,reftotalnumberofclusters); //number of sectors per clusterDiskinfo.sectorspercluster =SectorsPerCluster;//per sector byteDiskinfo.bytespersector =BytesPerSector;returnDiskInfo;} //// <summary>///structure. Hard Drive information/// </summary> Public structdiskinfo{ Public stringRootpathname;//number of sectors per cluster Public intSectorsPerCluster;//per sector byte Public intBytesPerSector; Public intnumberoffreeclusters; Public inttotalnumberofclusters;}/// <summary>///get the bytes per cluster/// </summary>/// <param name= "file" >Specify File</param>/// <returns></returns> Public Static Longgetclustersize (FileInfo file) {LongClustersize =0;D iskinfo DiskInfo=Newdiskinfo ();d iskinfo=getdiskinfo (file. Directory.Root.FullName); Clustersize= (Diskinfo.bytespersector *diskinfo.sectorspercluster);returnClustersize;} /// <summary>///get the bytes per cluster/// </summary>/// <param name= "dir" >Specify directory</param>/// <returns></returns> Public Static Longgetclustersize (DirectoryInfo dir) {LongClustersize =0;D iskinfo DiskInfo=Newdiskinfo ();d iskinfo=Getdiskinfo (dir. Root.fullname); Clustersize= (Diskinfo.bytespersector *diskinfo.sectorspercluster);returnclustersize;}

C # Get the size of folders and files and how they occupy space

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.