Using ManagementObject to read filesize on disk

Viewed 37

I have the following case, where I get an error using the .First() in ManagementObject variable, however, I can't figure out how to correct it. Can anyone help me? (using System.Management reference in project)

        public static long GetFileSizeOnDisk(string file)
    {
        FileInfo info = new FileInfo(file);
        uint clusterSize;

        var searcher = new ManagementObjectSearcher("select BlockSize,NumberOfBlocks from Win32_Volume WHERE DriveLetter = '" + info.Directory.Root.FullName.TrimEnd('\\') + "'")
            
        clusterSize = (uint)((ManagementObject)searcher.Get().First())["BlockSize"];

        uint hosize;
        uint losize = GetCompressedFileSizeW(file, out hosize);
        long size = (long) hosize << 32 | losize;
    
        return ((size + clusterSize - 1) / clusterSize) * clusterSize;
    }

Having also

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

The error is:

Error   CS1061  'ManagementObjectCollection' does not contain a definition for 'First' and no accessible extension method 'First' accepting a first argument of type 'ManagementObjectCollection' could be found (are you missing a using directive or an assembly reference?)
1 Answers

You need to convert it to something that Linq understands:

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

    static void Main()
    {
        var x = GetFileSizeOnDisk("d:\\x.jpg");
        Console.WriteLine(x);
    }


    public static ulong GetFileSizeOnDisk(string file)
    {
        FileInfo info = new FileInfo(file);
        ulong clusterSize = 4096;

        var searcher = new ManagementObjectSearcher("select BlockSize,NumberOfBlocks from Win32_Volume WHERE DriveLetter = '" + info.Directory.Root.FullName.TrimEnd('\\') + "'");

        var mo = (searcher.Get() as ManagementObjectCollection).OfType<ManagementObject>().FirstOrDefault();

        if(mo != null)
            clusterSize = (ulong)mo["BlockSize"];

        uint hosize;
        uint losize = GetCompressedFileSizeW(file, out hosize);
        ulong size = hosize << 32 | losize;

        var res = ((size + clusterSize - 1) / clusterSize) * clusterSize;

        return res;
    }
}
Related