Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file size without using System.IO.FileInfo?

Is it possible to get the size of a file in C# without using System.IO.FileInfo at all?

I know that you can get other things like Name and Extension by using Path.GetFileName(yourFilePath) and Path.GetExtension(yourFilePath) respectively, but apparently not file size? Is there another way I can get file size without using System.IO.FileInfo?

The only reason for this is that, if I'm correct, FileInfo grabs more info than I really need, therefore it takes longer to gather all those FileInfo's if the only thing I need is the size of the file. Is there a faster way?

like image 493
sergeidave Avatar asked Jan 18 '13 21:01

sergeidave


1 Answers

A quick'n'dirty solution if you want to do this on the .NET Core or Mono runtimes on non-Windows hosts:

Include the Mono.Posix.NETStandard NuGet package, then something like this...

using Mono.Unix.Native;

private long GetFileSize(string filePath)
{
    Stat stat;
    Syscall.stat(filePath, out stat);
    return stat.st_size;
}

I've tested this running .NET Core on Linux and macOS - not sure if it works on Windows - it might, given that these are POSIX syscalls under the hood (and the package is maintained by Microsoft). If not, combine with the other P/Invoke-based answer to cover all platforms.

When compared to FileInfo.Length, this gives me much more reliable results when getting the size of a file that is actively being written to by another process/thread.

like image 116
Mark Beaton Avatar answered Sep 19 '22 15:09

Mark Beaton