In this blog post, we will see how we can get the size of a file in C#.
To get a file size in C#, we have to use the .Length
property on the FileInfo
.
Get File Size In C# Using FileInfo.Length
Property
To calculate the size of a file in C#, we use the FileInfo class. We use the path of the file on the disk.
Let's understand how we can get the file size in C# using an example.
Example:
namespace ConsoleApp3 { public class Program { public static void Main() { FileInfo fileInfo = new FileInfo(@"C:\sample.txt"); long size = fileInfo.Length; Console.WriteLine($"File size in bytes is: {size}"); } } }
Result:
File size in bytes is: 1567
In the above code example, we can see that we create a FileInfo
object from the path of the file on the disk.
From this FileInfo
object, we use the .Length
property to get the size of the file in bytes.