简体   繁体   English

如何仅读取字符串的一部分以获得驱动器的序列号?

[英]How to read only a part of a string to obtain a drive's serial number?

I have a string with hard drive volume information (the message is displayed in a message box) 我有一个包含硬盘驱动器容量信息的字符串(该消息显示在消息框中)

Volume In Drive E is NEW VOLUME 驱动器E中的音量是新音量
Volume Serial Number is 9AE4-F468 卷序列号是9AE4-F468

I want to read only "9AE4F468" without the dash, and display it in a message box. 我只想阅读不带破折号的“ 9AE4F468”,并将其显示在消息框中。

I tried using Substring(45,54) , but I keep getting a compilation error because the program is not reading it. 我尝试使用Substring(45,54) ,但是由于程序未在读取它,所以不断出现编译错误。

How can I retrieve that particular substring without the dash? 如何在没有破折号的情况下检索该特定子字符串?

Rather than being in the position where you have to use a substring to get at the disk volume serial number, you could use a method that gives you the correct string directly. 您不必使用必须使用子字符串来获取磁盘卷序列号的位置,而可以使用直接为您提供正确字符串的方法。

To use the following code, you must add to your assembly a reference to System.Management and then add a using System.Management to the top of the code file. 若要使用以下代码,必须在程序System.Management添加对System.Management的引用,然后在代码文件的顶部添加using System.Management

Then add this method: 然后添加此方法:

public string DiskVolumeSerialNumber(char driveLetter)
{
    ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + driveLetter +":\"");
    disk.Get();
    return disk["VolumeSerialNumber"].ToString();
}

Which you can call like this: 您可以这样称呼:

string serial = DiskVolumeSerialNumber('C');
Console.WriteLine(serial);

Assuming you want the last word only: 假设您只想要硬道理:

string lastWordNoDash = 
    myLongMessage.Substring(myLongMessage.LastIndexOf(" ") + 1).Replace("-", "");

if you are looking for the last word then shadow wizard solve the problem. 如果您正在寻找最后的答案,那么影子向导可以解决问题。

if you're having more then you can do 如果您有更多的话就可以做

string lineNeeded = "Volume Serial Number is ";
string lastWordNoDash = 
    myLongMessage.Substring(myLongMessage.IndexOf(lineNeeded) + lineNeeded.length, 9).Replace("-", "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM