EN
C# / .NET - get file size
5 points
In this article, we're going to have a look at how to get file size in C# / .NET.
Quick solution:
xxxxxxxxxx
1
FileInfo file = new System.IO.FileInfo(@"C:\path\to\file.txt");
2
int fileSize = file.Length;
Look at the below code to see practical usage example:
In the presented solution FileInfo
class was used with Length
property that returns file size.
Note: if file was modified after
FileInfo
object was createdRefresh()
method should be called on the object to get current file inforamtions.
xxxxxxxxxx
1
using System;
2
using System.IO;
3
4
public static class Program
5
{
6
public static void Main(string[] args)
7
{
8
string path = @"C:\path\to\file.txt";
9
10
FileInfo info = new FileInfo(path);
11
Console.WriteLine("File size: " + info.Length + " bytes");
12
}
13
}
Output:
xxxxxxxxxx
1
File size: 46 bytes
In some cases when we use Length
property with specific stream, we need to be sure that the property is implemented - for File.Open
method result it is.
Note: this approach is useful when we have opened stream.
xxxxxxxxxx
1
using System;
2
using System.IO;
3
4
public class Program
5
{
6
public static void Main(string[] args)
7
{
8
string path = @"C:\path\to\file.txt";
9
10
using (FileStream stream = File.Open(path, FileMode.Open))
11
{
12
Console.WriteLine("File size: " + stream.Length + " bytes");
13
}
14
}
15
}
Output:
xxxxxxxxxx
1
File size: 46 bytes