Get size of a file in C#
This post will discuss how to get the size of a file in C#.
The System.IO namespace provides several classes pertaining to various common operations on files, directories, and streams. The FileInfo class provides several utility methods and properties for typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to files.
The recommended approach to retrieve the size of a file is using the FileInfo.Length property. It returns the size of the current file, in bytes. If the specified file does not exist, the FileNotFoundException is thrown. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\image.png"; long sizeInBytes = new FileInfo(path).Length; Console.WriteLine("Length is {0}", sizeInBytes); } } |
The following example displays the name and size of the specified file, using the Name and Length properties, respectively:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\image.png"; var f = new FileInfo(path); Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length); } } |
That’s all about getting the size of a file in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)