How do I retrieve disk information in C#?

前端 未结 6 1838
暖寄归人
暖寄归人 2020-11-27 18:25

I would like to access information on the logical drives on my computer using C#. How should I accomplish this? Thanks!

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 19:00

    In ASP .NET Core 3.1, if you want to get code that works both on windows and on linux, you can get your drives as follows:

    var drives = DriveInfo
        .GetDrives()
        .Where(d => d.DriveType == DriveType.Fixed)
        .Where(d => d.IsReady
        .ToArray();
    

    If you don't apply both wheres, you are going to get many drives if you run the code in linux (e.g. "/dev", "/sys", "/etc/hosts", etc.).

    This is specially useful when developing an app to work in a Linux Docker container.

提交回复
热议问题