Get file size without using System.IO.FileInfo?

前端 未结 6 1548
[愿得一人]
[愿得一人] 2021-02-13 15:51

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

6条回答
  •  醉酒成梦
    2021-02-13 16:07

    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.

提交回复
热议问题