C File Size Based on Extension Method of Extension Method

  • 2021-06-28 09:39:29
  • OfStack

An example of how C#obtains file size based on Extension Method (Extension Method).Share it for your reference.Specific analysis is as follows:

An Extension Method of the File Information Class that returns a formatted version of the file size.
For example: 1 GB or 100 B and it at max it will have two decimals.

Add the following code to a public static class in the same namespace, create a new FileInfo, and call GetFileSize.


/// <summary>
/// Gets a files formatted size.
/// </summary>
/// <param name="file">The file to return size of.</param>
/// <returns></returns>
public static string GetFileSize(this FileInfo file)
{
 try
 {
  //determine all file sizes
  double sizeinbytes = file.Length;
  double sizeinkbytes = Math.Round((sizeinbytes / 1024));
  double sizeinmbytes = Math.Round((sizeinkbytes / 1024));
  double sizeingbytes = Math.Round((sizeinmbytes / 1024));
  if (sizeingbytes > 1)
   return string.Format("{0} GB", sizeingbytes);
   //returns size in gigabytes
  else if (sizeinmbytes > 1)
   return string.Format("{0} MB", sizeinmbytes);
   //returns size in megabytes if less than one gigabyte
  else if (sizeinkbytes > 1)
   return string.Format("{0} KB", sizeinkbytes);
   //returns size in kilabytes if less than one megabyte
  else
   return string.Format("{0} B", sizeinbytes);
   //returns size in bytes if less than one kilabyte
 }
 catch { return "Error Getting Size"; }
 //catches any possible error and just returns error getting size
}

I hope that the description in this paper will be helpful to everyone's C#program design.


Related articles: