C# 在文件中查找特定文本并替换该文本

C# 在文件中查找特定文本并替换该文本,c#,wpf,replace,C#,Wpf,Replace,我正在构建一个WPF程序,该程序正在编辑模拟程序的保存文件,以便更容易地调整某些参数。该(txt)文件的结构如下所示 {Verdieping 1} A bunch of data 'Max' 15 20 10 ]); More data {Verdieping 2} A bunch of data 'Max' 25 10 40 20 ]); More data {Verdieping 3} etc. 因为我需要的列表的名称总是“Max”,所以我不能使用Replace(“旧值”

我正在构建一个WPF程序,该程序正在编辑模拟程序的保存文件,以便更容易地调整某些参数。该(txt)文件的结构如下所示

{Verdieping 1}

A bunch of data

'Max'
15
20
10
]);

More data

{Verdieping 2}

A bunch of data

'Max'
25
10
40
20
]);

More data

{Verdieping 3}

etc.
因为我需要的列表的名称总是“Max”,所以我不能使用
Replace(“旧值”、“新值”)所以我需要找到头{Verdieping 1},然后查找'Max',并写下值,直到它达到“]);“所以我最终得到了这样的结果:

Verdieping_1[0] = 15
Verdieping_1[1] = 20
Verdieping_1[0] = 10

Verdieping_2[0] = 25
Verdieping_2[1] = 10
Verdieping_2[2] = 40
Verdieping_2[3] = 20
然后,当我更改这些值时,我需要将它们写回文件中的正确位置。现在,我使用以下代码来读取并最终写入新文件:

var Model = System.IO.File.ReadAllText(@"C:\Base_Model.txt");

//format code here...

System.IO.File.WriteAllText(@"C:\New_Model.txt", Model);
有人能给我一些提示或帮助我如何才能最好地解决这个问题吗

编辑 这是我要编辑的文件的实际文件结构:

{Atom: Verdieping 2}

int015(0, 64, [ 
1
2
3
]);
int015(1, 64, [`ActivityID`
20
21
33
]);
int015(2, 64, [`vtp`
139830296
189540320
169919424
]);
int015(3, 64, [`%`
100
100
100
]);
int015(4, 64, [`Max`
15
5
20
]);
int015(5, 64, [`Fill (1 = fill, 0 = empty)`
1
1
0
]);
SetStatus(0);
int018;


{Atom: Verdieping 2}

int015(0, 64, [ 
1
2
3
]);
int015(1, 64, [`ActivityID`
22
23
24
]);
int015(2, 64, [`vtp`
166058172
165557860
155960564
]);
int015(3, 64, [`%`
100
100
100
]);
int015(4, 64, [`Max`
15
20
10
]);
int015(5, 64, [`Fill (1 = fill, 0 = empty)`
0
1
1
]);
SetStatus(0);
int018;
我之前提到的“Max”实际上被称为: int015(4,64,[
Max

正如你所看到的,每个层的名称都是相同的,变量的数量是不同的


<>谢谢你的帮助!

< P>正则表达式也许吧?我做了这个快速答案,不应该是复制粘贴的,但是,你可以考虑结果。

在这个回答中,我希望您的数组按时间顺序排列,以避免源代码过长和混乱

我为“DataContainer”对象读取的文件看起来与下面的文件相同:

{Verdieping 1}

A bunch of data

'Max'
15
20
10
]);

More data

{Verdieping 2}

A bunch of data

'Max'
25
10
40
20
]);
首先,我在字符串中找到每个“Max” 然后我把下面所有的数据都打印出来

用于查找此项的正则表达式是:
\'Max\'.*?\]\);

请尝试此代码以查看结果

// fill our container
            string DataContainer = string.Empty;
            using (StreamReader sr = new StreamReader(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TestFile.txt"))) {
                DataContainer = sr.ReadToEnd();
            }

            // print data
            Match regMatch = Regex.Match(DataContainer, @"\'Max\'.*?\]\);", RegexOptions.Singleline);
            int verdiepc = 0;
            while (regMatch.Success) {
                string[] Data = regMatch.Value.Replace("\r", "").Split('\n');

                for (int I = 1; I < Data.Length - 1; I++) {
                    Console.WriteLine("Verdieping_{0}[{1}] = {2}"
                        , verdiepc, I, Data[I]);
                }
                Console.Write("\n");

                verdiepc ++;
                regMatch = regMatch.NextMatch();
            }

            // prevent immidiate exit
            Console.ReadKey();
我希望您能使用这个答案。这是一个如何使用正则表达式解析文件的草图

string LoadedFile=file.ReadAllText(@“C:\Base_Model.txt”);
        string LoadedFile = File.ReadAllText(@"C:\Base_Model.txt");
        StringBuilder result = new StringBuilder();
        for (int i = 1; i < Int32.MaxValue; i++)
        {
            Match ma = Regex.Match(LoadedFile, "Verdieping " + i.ToString() + ".+?'Max'.*?([0-9].+?)[]][)];", RegexOptions.Singleline);
            if(!ma.Success)
            {
                break;
            }
            string a = ma.Result("$1");
            MatchCollection mc = Regex.Matches(a, "(\\d+?)\r\n", RegexOptions.Singleline);

            for (int j = 0; j < mc.Count; j++)
            {
                result.AppendLine(String.Format("Verdieping_{0}[{1}] = {2}", i, j, mc[j].Result("$1")));
            }
            result.AppendLine(String.Empty);
        }

        File.WriteAllText(@"C:\New_Model.txt", result.ToString());
StringBuilder结果=新建StringBuilder(); 对于(inti=1;i
您可以初始化一个新的
列表
字符串
,该列表将包含所需的输出。然后,阅读文件,获取目标部分之间的信息,并插入
[
]之间的值;
字符串
列表中

示例

static List<string> ReadFile(string Path, string Section)
{
    #region Declare Variables
    string[] Lines = File.ReadAllLines(Path); //Read Path into Lines
    int CurrentValue = 1; //Declare CurrentValue as an Integer of value 1
    List<string> RequiredValues = new List<string>(); //Initialize a new List of string of name RequiredValues
    #endregion
    #region Collect Information
    //Look through the section getting the data between [ and ]);
    for (int i = 0; i < Lines.Length; i++)
    {
        if (Lines[i].StartsWith("{" + Section + "}"))
        {
            i++;
            while (!Lines[i].StartsWith("{") && !Lines[i].EndsWith("}"))
            {
                i++;
                if (Lines.Length > i)
                {
                    if (Lines[i].Contains('['))
                    {
                        while (true)
                        {

                            i++;
                            if (Lines[i].Contains("]);"))
                            {
                                break;
                            }
                            RequiredValues.Add(Section + "[" + CurrentValue.ToString() + "] = " + Lines[i]);
                            CurrentValue++;
                        }
                    }
                    RequiredValues.Add("");
                }
                else
                {
                    break; //Reached the end of the document
                }
            }
        }
    }
    #endregion
    return RequiredValues; //Return RequiredValues
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    List<string> Contents = ReadFile(@"C:\Base_Model.txt", "Atom: Verdieping 2");
    foreach (string str in Contents)
    {
        System.Diagnostics.Debug.WriteLine(str); //Write str to the trace listeners
    }
}
样本输出

读取原子时返回以下内容:判定2

原子:判定2[1]=4 原子:判定2[2]=5 原子:判定2[3]=6 原子:判定2[4]=20 原子:判定2[5]=21 原子:判定2[6]=33 原子:判定2[7]=139830296 原子:判定2[8]=189540320 原子:判定2[9]=169919424 原子:判定2[10]=100 原子:判定2[11]=100 原子:判定2[12]=100 原子:判定2[13]=15 原子:判定2[14]=5 原子:判定2[15]=20 原子:判定2[16]=1 原子:判定2[17]=1 原子:判定2[18]=0
读取原子时返回以下输出:判定1

原子:判定1[1]=1 原子:判定1[2]=2 原子:判定1[3]=3 原子:判定1[4]=22 原子:判定1[5]=23 原子:判定1[6]=24 原子:判定1[7]=166058172 原子:判定1[8]=165557860 原子:判定1[9]=155960564 原子:判定1[10]=100 原子:判定1[11]=100 原子:判定1[12]=100 原子:判定1[13]=15 原子:判定1[14]=20 原子:判定1[15]=10 原子:判定1[16]=0 原子:判定1[17]=1 原子:判定1[18]=1
注意:使用此方法,应用程序将只收集它遇到的第一个部分之间的信息,即使您有两个名称相同的部分

谢谢,

我希望你会觉得这很有帮助:)

“一些想法?”听起来像是解析器。听起来你应该使用Xml而不是文本文件。应该有一些代码来生成这个文本文件。它的算法/逻辑是什么?@L.B将a
regexp
help OP?@bonCodigo可能,但是跳过的部分(
一堆数据
)可能会给我们文本文件的结构。如果不知道整个结构,所有的答案都将是蹩脚的。
var result = Regex.Matches(File.ReadAllText(fileName), @"\[`Max`(.*?)\]", RegexOptions.Singleline)
            .Cast<Match>()
            .Select(m => m.Groups[1].Value.Split(" \t\n\r".ToArray(), StringSplitOptions.RemoveEmptyEntries))
            .ToList();

foreach (var v in result)
{
    Console.WriteLine(String.Join(", ", v));
}
15, 5, 20
15, 20, 10
static List<string> ReadFile(string Path, string Section)
{
    #region Declare Variables
    string[] Lines = File.ReadAllLines(Path); //Read Path into Lines
    int CurrentValue = 1; //Declare CurrentValue as an Integer of value 1
    List<string> RequiredValues = new List<string>(); //Initialize a new List of string of name RequiredValues
    #endregion
    #region Collect Information
    //Look through the section getting the data between [ and ]);
    for (int i = 0; i < Lines.Length; i++)
    {
        if (Lines[i].StartsWith("{" + Section + "}"))
        {
            i++;
            while (!Lines[i].StartsWith("{") && !Lines[i].EndsWith("}"))
            {
                i++;
                if (Lines.Length > i)
                {
                    if (Lines[i].Contains('['))
                    {
                        while (true)
                        {

                            i++;
                            if (Lines[i].Contains("]);"))
                            {
                                break;
                            }
                            RequiredValues.Add(Section + "[" + CurrentValue.ToString() + "] = " + Lines[i]);
                            CurrentValue++;
                        }
                    }
                    RequiredValues.Add("");
                }
                else
                {
                    break; //Reached the end of the document
                }
            }
        }
    }
    #endregion
    return RequiredValues; //Return RequiredValues
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    List<string> Contents = ReadFile(@"C:\Base_Model.txt", "Atom: Verdieping 2");
    foreach (string str in Contents)
    {
        System.Diagnostics.Debug.WriteLine(str); //Write str to the trace listeners
    }
}