microsoft / dotnet

This repo is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.
https://devblogs.microsoft.com/dotnet/
MIT License
14.31k stars 2.21k forks source link

How to get external disk by net6.0 #1376

Open HanaSongem opened 1 year ago

HanaSongem commented 1 year ago

i get External disk by WMI API in .net6.0 program,

disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive")

but it didn't work in windows 7 ,it throws expection The type initializer for 'System.Management.ManagementPath' threw an exception because its depands on .net framework 4.7,but windows 7 only have .net framework 4.0 I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

Thanks in advance.

tarizshahid commented 10 months ago

The error you're encountering is due to the fact that the System.Management namespace in .NET 6.0 relies on .NET Framework 4.7 or later to work correctly. Windows 7, as you mentioned, only comes with .NET Framework 4.0 by default, so you won't be able to use this particular part of the .NET 6.0 framework on Windows 7

you can use a different approach to query disk drive information on Windows 7 without relying on .NET 6.0's System.Management namespace. One option is to use the DriveInfo class from the System.IO namespace

DriveInfo[] allDrives = DriveInfo.GetDrives();

    foreach (DriveInfo drive in allDrives)
    {
        Console.WriteLine("Drive: " + drive.Name);
        Console.WriteLine("Drive Type: " + drive.DriveType);
        Console.WriteLine("Drive Format: " + drive.DriveFormat);
        Console.WriteLine("Total Size: " + drive.TotalSize);
        Console.WriteLine("Available Space: " + drive.AvailableFreeSpace);
    }