C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: The code creates a new FileInfo—this allows us to get the file size. We use the Length property and a long value.
Part 2: We print the size of the file with Console.WriteLine. The sizes are in bytes.
ConsoleTip: Make sure to update the path to a file that exists on your computer before running the program.
C# program that gets file size
using System;
using System.IO;
class Program
{
static void Main()
{
const string fileName = @"C:\programs\file.txt";
// Part 1: create new FileInfo get Length.
FileInfo info = new FileInfo(fileName);
long length = info.Length;
// Part 2: print length in bytes.
Console.WriteLine("LENGTH IN BYTES: {0}", length);
}
}
Output
LENGTH IN BYTES: 60
Part 1: We get the info objects for the specified I rectory. We call GetFileSystemInfos.
Part 2: We loop over the objects and get each individual FileInfo and then access the Length. We sum these values and return the sum.
ForC# program that gets directory size
using System;
using System.IO;
class Program
{
static int GetDirectorySize(string path)
{
// Part 1: get info.
DirectoryInfo directoryInfo = new DirectoryInfo(path);
FileSystemInfo[] array = directoryInfo.GetFileSystemInfos();
// Part 2: sum all FileInfo Lengths.
int sum = 0;
for (int i = 0; i < array.Length; i++)
{
FileInfo fileInfo = array[i] as FileInfo;
if (fileInfo != null)
{
sum += (int)fileInfo.Length;
}
}
return sum;
}
public static void Main()
{
Console.WriteLine("SIZE: {0}", GetDirectorySize(@"C:\programs\"));
}
}
Output
SIZE: 96035