Wednesday, June 17, 2026

C# How to get FIle size of a file

The following code shows how to get the size of a file in bytes and megabytes. The Length property of FileStream helps to get the file size.
class Demo
{
    static void Main()
    {
        var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string filepath = Path.Combine(mydocs, "test.txt");
        if (File.Exists(filepath))
        {
            FileStream fileStream = File.Open(filepath, FileMode.Open);
            Console.WriteLine($"File size in bytes: {fileStream.Length}");
            Console.WriteLine($"File size in Mega bytes: {(double)fileStream.Length / 1024}");
        }
        var pictures = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
        filepath = Path.Combine(pictures, "ganga.jpg");
        if (File.Exists(filepath))
        {
            FileStream fileStream = File.Open(filepath, FileMode.Open);
            Console.WriteLine($"File size in bytes: {fileStream.Length}");
            Console.WriteLine($"File size in Mega bytes: {(double)fileStream.Length / 1024}");
        }
    }
}

No comments:

Post a Comment

Hot Topics