Get SerialHdd C# using CMD

0 thích 0 không thích
1 lượt xem
đã hỏi 30 Tháng 6, 2023 trong Lập trình C# bởi nguyenthao (9,040 điểm)
using System;
using System.Collections.Generic;
using System.Diagnostics;

public class HDDSerialNumberRetriever
{
    public List<string> GetAllHDDSerialNumbers()
    {
        List<string> serialNumbers = new List<string>();

        try
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = "wmic";
            processStartInfo.Arguments = "diskdrive get SerialNumber";
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute = false;
            processStartInfo.CreateNoWindow = true;

            Process process = Process.Start(processStartInfo);

            // Read the standard output of the command
            string output = process.StandardOutput.ReadToEnd();

            // Parse the output and extract the serial numbers
            string[] lines = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 1; i < lines.Length; i++)
            {
                string serialNumber = lines[i].Trim();
                serialNumbers.Add(serialNumber);
            }
        }
        catch (Exception ex)
        {
            // Handle any exceptions that occur during the retrieval
            Console.WriteLine("An error occurred while retrieving HDD serial numbers: " + ex.Message);
        }

        return serialNumbers;
    }
}

Cách sử dụng:

HDDSerialNumberRetriever serialNumberRetriever = new HDDSerialNumberRetriever();
List<string> serialNumbers = serialNumberRetriever.GetAllHDDSerialNumbers();

// Display the serial numbers
foreach (string serialNumber in serialNumbers)
{
    Console.WriteLine(serialNumber);
}

Looking for an answer?  Share this question:     

Xin vui lòng đăng nhập hoặc đăng ký để trả lời câu hỏi này.

...