用于在外部 C# 文件中搜索文本的代码
本文关键字:搜索 文本 代码 文件 外部 用于 | 更新日期: 2023-09-27 18:31:23
我们在设计器.cs文件中this.label1.Text = "Code Smart";
现在,我正在读取保存在解决方案文件夹中的所有.Designer.cs
文件。
现在我想满足这些条件:
- 如果在字符串中
.Text=
或.Text =
匹配或不匹配。 - 我想从该字符串中获取文本,该字符串在
"" (Double Quotes)
这意味着:Code Smart
背后的想法是收集文件中的所有.Text
数据,因此,如果我获得该文本的匹配数据和值,那么我会将其导出到CSV
进行翻译。
有人可以帮我这样做吗。
ADD1
我已经对 ADD1 进行了一些更改并已修改为 ADD2,请检查并发表评论。谢谢
ADD2:
好的,最后我到达了这个,让我知道如何在双引号内获取字符串:
FolderBrowserDialog fbd = new FolderBrowserDialog();
foreach (string file in Directory.EnumerateFiles(fbd.SelectedPath, "*.Designer.cs"))
{
int counter = 0;
string line;
// Read the file and display it line by line.
StreamReader CurrentFile = new StreamReader(file);
while ((line = CurrentFile.ReadLine()) != null)
{
bool typeOne = line.Contains(".Text=");
bool typeTwo = line.Contains(".Text =");
if ((typeOne == true) || (typeTwo == true))
{
// Get the data which is enclosed in double quotes
}
counter++;
}
CurrentFile.Close();
}
假设没有双引号的嵌套,您可以使用以下正则表达式:
'.Text's*='s*"([^"]+)"
IDEe演示
然后,我会将其导出为 CSV 进行翻译。
如果目标是拥有一个多语言 GUI,我不建议这样做。尝试使用 etither Zeta Resource Editor,或 Resx Resource Translator。
同时查看此资源:演练:本地化 Windows 窗体。它描述了如何创建可以使用 Zeta 或 Resx 编辑的多种语言资源文件。
希望这就是你试图实现的。如果没有,请忽略这个答案。
看看这是否有帮助;
foreach (string file in Directory.EnumerateFiles(fbd.SelectedPath, "*.Designer.cs"))
{
int counter = 0;
string line;
Regex r = new Regex(@"this.label1.Text[ ]*['=]{1}[ ]*['""]{1}(?<StringValue>[a-zA-Z0-9 ]*)['""]{1}[ ]*[';]{1}");
// Read the file and display it line by line.
StreamReader CurrentFile = new StreamReader(file);
while ((line = CurrentFile.ReadLine()) != null)
{
bool typeOne = line.Contains(".Text=");
bool typeTwo = line.Contains(".Text =");
if ((typeOne == true) || (typeTwo == true))
{
Match m=r.Match(line);
string thevalueyouneed=m.Groups[1].Value;//This is what you need.
//Do other things with this value.
}
counter++;
}
CurrentFile.Close();
}
第一组是您需要的字符串。
if ((typeOne == true) || (typeTwo == true))
{
int indexOfTheStartOfText = line.IndexOf(".Text", StringComparison.CurrentCulture);
if (indexOfTheStartOfText != -1)
{
int textLength = (typeOne == true) ? ".Text=".Length : ".Text =".Length;
int StartIndexOfActualText = indexOfTheStartOfText + textLength + "'"".Length;
int EndIndexOfActualText = line.IndexOf('"', StartIndexOfActualText);
string myText = line.Substring(StartIndexOfActualText, EndIndexOfActualText - StartIndexOfActualText);
}
}
StartIndexOfActualText
的计算需要因typeOne
或typeTwo
而更改