1

我有一个带有硬盘卷信息的字符串(消息显示在消息框中)

驱动器 E 中的
卷是新卷卷序列号是 9AE4-F468

我只想阅读没有破折号的“9AE4F468”,并将其显示在消息框中。

我尝试使用Substring(45,54),但由于程序没有读取它,所以我不断收到编译错误。

如何在没有破折号的情况下检索该特定子字符串?

4

3 回答 3

4

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.

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);
于 2013-08-11T08:57:06.100 回答
2

假设您只想要最后一句话:

string lastWordNoDash = 
    myLongMessage.Substring(myLongMessage.LastIndexOf(" ") + 1).Replace("-", "");
于 2013-08-11T08:46:53.840 回答
0

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("-", "");
于 2013-08-11T08:58:18.070 回答