How to Get File Size in C# .NET

c get file size Get File Size in C Get File Size in CNET

In this article, we will see a simple way to Get File Size in C#.NET.

We will be using a very useful class FileInfo available in C#.NET.

We will cover below aspects,

FileInfo class provides properties and instance methods while dealing with the file,

  • Directory – retrieves an object that represents the parent directory of a file.
  • DirectoryName – retrieves the full path of the parent directory of a file.
  • Exists – checks for the presence of a file.
  • IsReadOnly – gets or sets a value that specifies whether a file can be modified.
  • Length -gets the size of a file.
  • The name gets the name of a file.

Below is a sample method that will give you file size in bytes which you can convert to KB or MB size as required.

 
static long GetFileSize(string FilePath)
        {
            if (File.Exists(FilePath))
            {
                return new FileInfo(FilePath).Length;
            }
            return 0;
        }

FileInfo class has a length property that gives the size, in bytes, of the current file.

            int bytesRead;

            string filePath = @"C:\Test\File\file-input- 
            thecodebuzz.txt";


            long fileSizeibBytes = GetFileSize(filePath);
            

C# Get file size in Bytes

long fileSizeibBytes = GetFileSize(filePath);

C# Get file size in KB

Below is an example to get file size in KB using C#,

long fileSizeibKbs = fileSizeibBytes / 1024;

C# get file size in MB or GB

long fileSizeibMbs = fileSizeibBytes / (1024*1024);

References :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *