How to choose the right disk size

I am trying to get the physical device size of a connected USB flash drive. I tried using WMI.

        ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
        foreach (ManagementObject moDisk in mosDisks.Get())
        {
            lblCapacity.Text = "Capacity: " + moDisk["Size"];
        }

I tried using import to get the geometry:

        var geo = new DiskGeometry();
        uint returnedBytes;
        DeviceIoControl(Handle, 0x70000, IntPtr.Zero, 0, ref geo, (uint)Marshal.SizeOf(typeof(DiskGeometry)), out returnedBytes, IntPtr.Zero);
        return geo.DiskSize;

They all return a value .. but this is not true.

For example, the above code returns 250056737280. When I upload all the binary contents to a new file, FileStream.Length returns 250059350015

See how the last option is bigger? This is also the correct size, which I need for my code to work as expected. But I can not reset 250 GB of data to get the full size. So, is there any other way to get the right size?

+3
source share
2

, IOCTL_DISK_GET_LENGTH_INFO DevideIoControl.

+1

?

using System;
using System.Runtime.InteropServices;

public class MainClass
{
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
       out ulong lpFreeBytesAvailable,
       out ulong lpTotalNumberOfBytes,
       out ulong lpTotalNumberOfFreeBytes);
    public static void Main()
    {
        ulong freeBytesAvail;
        ulong totalNumOfBytes;
        ulong totalNumOfFreeBytes;

        if (!GetDiskFreeSpaceEx("C:\\", out freeBytesAvail, out totalNumOfBytes, out totalNumOfFreeBytes))
        {
            Console.Error.WriteLine("Error occurred: {0}",
                Marshal.GetExceptionForHR(Marshal.GetLastWin32Error()).Message);
        }
        else
        {
            Console.WriteLine("Free disk space:");
            Console.WriteLine("    Available bytes : {0}", freeBytesAvail);
            Console.WriteLine("    Total # of bytes: {0}", totalNumOfBytes);
            Console.WriteLine("    Total free bytes: {0}", totalNumOfFreeBytes);
        }
    }
}

: http://www.java2s.com/Tutorial/CSharp/0520__Windows/Getfreediskspace.htm

. .

0

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


All Articles