Get file size in bytes in C# using the FileInfo.Length property
Get File Size in C#.
How to get a file size in bytes using C# using the FileInfo.Length property.
The size of any file in bytes can be returned by the Length property of FileInfo Class. Following code returns the size of file:
// To Get size of any file
long FileSize = MyFile.Length;
Console.WriteLine("File Size in Bytes: {0}", FileSize);
Here, to run it we must import System.IO and System.Text namespaces in the project.
Coding Implementation
Here is the complete coding implementation. Here we use FileInfo class to create an object by passing a complete File location with its name. FileInfo class allows us to get information about a file. Such as: file name, size, full path, extension, directory name, is file read only or not, File creation date, updated date etc.
Note: we can convert the size from bytes to KB, MB, and GB by dividing bytes by 1024, 1024x1024 and so on.
using System;
using System.IO;
using System.Text;
namespace FileSize
{
class Program
{
static void Main(string[] args)
{
// Full file name
string filePath = @"C:\Users\SIW\Documents\TestFile.txt";
FileInfo MyFile = new FileInfo(filePath);
// Create a new file
using (FileStream fs = MyFile.Create())
{
Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");
fs.Write(txt, 0, txt.Length);
Byte[] author = new UTF8Encoding(true).GetBytes("Author TTMind Community");
fs.Write(author, 0, author.Length);
}
// Get File Name
string justFileName = MyFile.Name;
Console.WriteLine("File Name: {0}", justFileName);
// Get file name with full path
string fullFileName = MyFile.FullName;
Console.WriteLine("File Name: {0}", fullFileName);
// Get file extension
string extn = MyFile.Extension;
Console.WriteLine("File Extension: {0}", extn);
// Get directory name
string directoryName = MyFile.DirectoryName;
Console.WriteLine("Directory Name: {0}", directoryName);
// File Exists ?
bool exists = MyFile.Exists;
Console.WriteLine("File Exists: {0}", exists);
if (MyFile.Exists)
{
//To Get Size of any file
long size = MyFile.Length;
Console.WriteLine("File Size in Bytes: {0}", size);
//is our File ReadOnly ?
bool IsReadOnly = MyFile.IsReadOnly;
Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);
//get Creation, last access, and last write time
DateTime creationTime = MyFile.CreationTime;
Console.WriteLine("Creation time: {0}", creationTime);
DateTime accessTime = MyFile.LastAccessTime;
Console.WriteLine("Last access time: {0}", accessTime);
DateTime updatedTime = MyFile.LastWriteTime;
Console.WriteLine("Last write time: {0}", updatedTime);
}
}
}
}
Output: