C # .net Core - get file size on disk - cross-platform solution

Is there a way to have common logic to get the size of the file on disk regardless of the operating system? The following code works for windows, but obviously not for Linux.

 public static long GetFileSizeOnDisk(string file)
    {
        FileInfo info = new FileInfo(file);
        uint dummy, sectorsPerCluster, bytesPerSector;
        int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy);
        if (result == 0) throw new Win32Exception();
        uint clusterSize = sectorsPerCluster * bytesPerSector;
        uint hosize;
        uint losize = GetCompressedFileSizeW(file, out hosize);
        long size;
        size = (long)hosize << 32 | losize;
        return ((size + clusterSize - 1) / clusterSize) * clusterSize;
    }

    [DllImport("kernel32.dll")]
    static extern uint GetCompressedFileSizeW([In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
       [Out, MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh);

    [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)]
    static extern int GetDiskFreeSpaceW([In, MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName,
       out uint lpSectorsPerCluster, out uint lpBytesPerSector, out uint lpNumberOfFreeClusters,
       out uint lpTotalNumberOfClusters);

Alternatively, I am looking for a similar implementation that will work on Linux. Can someone point me in the right direction?

Thank you for your help!

+4
source share
1 answer

To calculate the file size on disk, you can use the following formula.

long size = cluster * ((fileLength + cluster - 1) / cluster);

PInvoke , GetDiskFreeSpace. , , , .

DriveInfo. , , PInvoke, .Net.

+2

Source: https://habr.com/ru/post/1693330/


All Articles