How do you get the file size in C#?
Asked Answered
W

9

430

I need a way to get the size of a file using C#, and not the size on disk. How is this possible?

Currently I have this loop

foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
    //file.Length (will this work)
}

Will this return the size or the size on disk?

Wahhabi answered 4/9, 2009 at 18:32 Comment(1)
Related, but for VB.NET: Determining file size in VB.NET,Eastbound
G
435

FileInfo.Length will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.

Gilding answered 4/9, 2009 at 18:34 Comment(5)
Also: social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/… this is a discussion about how to get "the other value", which is size on disk.Unlimber
There is no method "FileInfo.Length"! Remember that you specified call of STATIC METHOD. Real answer is new FileInfo(path).Length what can be heavy for mass operation.Harim
FWIW @Harim - Yes and No. FileInfo.Length is how the doc refers to the property, even though it is not static. The answer is relative to the code in question. Consider how one typically does a "mass operation" - via the directory info: ... new DirectoryInfo(...).GetFiles(); A collection of FileInfos is created for you. Getting Length of all those files is lightweight.Honeysweet
@ToolmakerSteve: MS docs is well-known rubbish, don't refer it as a "normal way". Newbies will be confused when they see call to static method and obviously it doesn't exist. GetFiles() is only one of ways to get list of files. Names could be autogenerated (like "pic15.jpg", "pic16.jpg"...) - then you need to call FileInfo every time. In any case OS keeps cache of directories and getting length MUST NOT be heavy operation as "create object" - length can be obtained directly by call like FileInfo.GetLength(string fileName). It's WAY more convenient and suits to many casual tasks.Harim
@Viincent - "Names could be autogenerated (like "pic15.jpg", "pic16.jpg"...) - then you need to call FileInfo every time. " That's almost never necessary, for a "mass operation". Extract the directory path of all the file paths, into a HashSet. I'd love to know about a static method that gives Length of file. What environment are you in, that has FileInfo.GetLength? Neither Google nor Intellisense is giving me a hit for any static member, on either File or FileInfo, that gives file length.Honeysweet
A
587

If you have already a file path as input, this is the code you need:

long length = new System.IO.FileInfo(path).Length;
Artful answered 31/12, 2013 at 20:53 Comment(1)
Surround it with try/catch block and check all possible exceptions as described here: SecurityException, UnauthorizedAccessException, PathTooLongException, NotSupportedException and - dependend on your use case - ArgumentNullException and ArgumentExceptionGoogins
G
435

FileInfo.Length will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.

Gilding answered 4/9, 2009 at 18:34 Comment(5)
Also: social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/… this is a discussion about how to get "the other value", which is size on disk.Unlimber
There is no method "FileInfo.Length"! Remember that you specified call of STATIC METHOD. Real answer is new FileInfo(path).Length what can be heavy for mass operation.Harim
FWIW @Harim - Yes and No. FileInfo.Length is how the doc refers to the property, even though it is not static. The answer is relative to the code in question. Consider how one typically does a "mass operation" - via the directory info: ... new DirectoryInfo(...).GetFiles(); A collection of FileInfos is created for you. Getting Length of all those files is lightweight.Honeysweet
@ToolmakerSteve: MS docs is well-known rubbish, don't refer it as a "normal way". Newbies will be confused when they see call to static method and obviously it doesn't exist. GetFiles() is only one of ways to get list of files. Names could be autogenerated (like "pic15.jpg", "pic16.jpg"...) - then you need to call FileInfo every time. In any case OS keeps cache of directories and getting length MUST NOT be heavy operation as "create object" - length can be obtained directly by call like FileInfo.GetLength(string fileName). It's WAY more convenient and suits to many casual tasks.Harim
@Viincent - "Names could be autogenerated (like "pic15.jpg", "pic16.jpg"...) - then you need to call FileInfo every time. " That's almost never necessary, for a "mass operation". Extract the directory path of all the file paths, into a HashSet. I'd love to know about a static method that gives Length of file. What environment are you in, that has FileInfo.GetLength? Neither Google nor Intellisense is giving me a hit for any static member, on either File or FileInfo, that gives file length.Honeysweet
A
45

FileInfo.Length will do the trick (per MSDN it "[g]ets the size, in bytes, of the current file.") There is a nice page on MSDN on common I/O tasks.

Alderman answered 4/9, 2009 at 18:34 Comment(0)
P
14

MSDN FileInfo.Length says that it is "the size of the current file in bytes."

My typical Google search for something like this is: msdn FileInfo

Polyphyletic answered 4/9, 2009 at 18:35 Comment(0)
C
11

The FileInfo class' Length property returns the size of the file (not the size on disk). If you want a formatted file size (i.e. 15 KB) rather than a long byte value you can use CSharpLib, a package I've made that adds more functionality to the FileInfo class. Here's an example:

using CSharpLib;
FileInfo info = new FileInfo("sample.txt");
Console.WriteLine(info.FormatBytes());  // Output: 15 MB
Creeper answered 7/6, 2020 at 22:48 Comment(0)
M
5

It returns the file contents length

Marx answered 4/9, 2009 at 18:34 Comment(0)
M
4

Size on disk might be different, if you move the file to another filesystem (FAT16, NTFS, EXT3, etc)

As other answerers have said, this will give you the size in bytes, not the size on disk.

Marotta answered 4/9, 2009 at 18:37 Comment(0)
U
1
long l = new System.IO.FileInfo(path).Length;
string l_ = Formatter(l); // Example: "67 Mb"

//

public string Formatter(long input)
    {
        string output;
        switch (input.ToString().Length)
        {
            case > 12:
                output = input / 1000000000000 + " Tb";
                break;
            case > 9:
                output = input / 1000000000 + " Gb";
                break;
            case > 6:
                output = input / 1000000 + " Mb";
                break;
            case > 3:
                output = input / 1000 + " Kb";
                break;
            default:
                output = input + " b";
                break;
        }
        return output;
    }
Uniformity answered 23/10, 2023 at 14:33 Comment(0)
M
-1

Thanks to JLRishe's answer. Here is my edited code for your convenience.

public static class QuickImgSize
{
    //https://mcmap.net/q/81994/-does-net-provide-an-easy-way-convert-bytes-to-kb-mb-gb-etc
    private static string[] S_SIZE_SUFFIXES =
               { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
    private static string SizeSuffix(long value, int decimalPlaces = 2)
    {
        if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
        if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }
        if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

        // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
        int mag = (int)Math.Log(value, 1024);

        // 1L << (mag * 10) == 2 ^ (10 * mag) 
        // [i.e. the number of bytes in the unit corresponding to mag]
        decimal adjustedSize = (decimal)value / (1L << (mag * 10));

        // make adjustment when the value is large enough that
        // it would round up to 1000 or more
        if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
        {
            mag += 1;
            adjustedSize /= 1024;
        }

        return string.Format("{0:n" + decimalPlaces + "} {1}",
            adjustedSize,
            S_SIZE_SUFFIXES[mag]);
    }

    public static string GetFileSize(string szPath)
    {
        var fileInfo = new FileInfo(szPath);
        return SizeSuffix(fileInfo.Length);
    }
}

Usage:

Console.WriteLine(QuickImgSize.GetFileSize(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"));
Mariel answered 24/1 at 17:34 Comment(1)
Would you explain your "edit"?Trincomalee

© 2022 - 2024 — McMap. All rights reserved.