我有一个 .cs 文件列表,每个文件都包含一个字符串 commandID。我需要检索这个字符串的值。
如何在 C# 中实现这种搜索和检索值机制?
//Sample code to list all .cs files within a directory
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.cs");
// Sample code to read 1 file.
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\file1.cs");
// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
// INSERT YOUR SEARCH LOGIC HERE
}
终于得到了 ID :)
假设你找到了你想要的行,所以我从行中得到了 ID,如下所示:
string line = "while(i<10){CommandID = 15852; i+=1;}";
//I've put a complicated code in the string to make you sure
var rightSideOfAssignment = line.Split(new string[] {"CommandID"}, StringSplitOptions.RemoveEmptyEntries)[1];
int val = 0,temp;
bool hasAlreadyStartedFetchingNumbers= false;
foreach (char ch in rightSideOfAssignment) //iterate each charachter
{
if (int.TryParse(ch.ToString(), out temp)) //if ch is a number
{
foundFirstInteger = true;
val *= 10;
val += temp;
}
else
{
if (hasAlreadyStartedFetchingNumbers)
break;
//If you don't check this condition, it'll result to 158521
//because after hitting `;` it won't stop searching
}
}
MessageBox.Show(val.ToString()); //shows 15852
我假设,在您的项目中的 .Cs 文件中有一些名为 CommandId 的字符串,您正在尝试获取它的值,因为您不想手动转到每个文件并获取它的值。
遵循以下
1- 将所有 .CS 文件粘贴到单独的文件夹中。
2- 使用 FileSytem 获取该文件夹中的所有文件
3- 使用流阅读器获取 .cs 文件中的文本
4-将文件中的每一行与您要查找的文本进行比较。
5- 如果字符串匹配,则将其保存在 XML 或其他文本文件之类的位置。
6- 阅读下一个文件并返回第 3 步。