Skip to content
Advertisement

C# .net Core – Get file size on disk – Cross platform solution

Is there a way to have a common logic to retrieve the file size on disk regardless of the underlying operating system ? The following code works for windows but obviously doesn’t 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’m looking for a similar implementation that would work on Linux. Can anyone point me in the right direction ?

Thanks for your help !

Advertisement

Answer

To calculate the size of a file on disk, you can utilize the following formula.

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

The tricky part would be to take the PInvoke approach above, then reference the proper library or file to achieve the GetDiskFreeSpace functionality. You would have to determine which platform the application is running, then invoke the specific system library to return the information so you can calculate the file size on disk.

You could also look at DriveInfo. But I’m not sure if that would give you the proper free space, but a thought and you wouldn’t need PInvoke since it is fully supported in .Net Standard.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement