【问题标题】:Modify/replace Text in tab-base text file in C#在 C# 中修改/替换基于选项卡的文本文件中的文本
【发布时间】:2016-10-22 21:23:48
【问题描述】:

这个问题是过去讨论HERE 的延续。所以现在我设法读取了我的文本文件中的每一行,并读取了某一列中的确切字符串。我现在的问题是,我希望用另一个字符串值修改 tab-base 文件的列 (4) 中的文本值。 比如原来的文件是这样的:

ID1 25  800 Low
ID2 25  700 Low
ID3 25  600 Low

我想改成:

ID1 25  800 High
ID2 25  700 High
ID3 25  600 High

…这是我的完整代码。感谢您的帮助。

string route = @"C:\MyFile.txt";
FileStream fileStream2 = new FileStream(route, FileMode.Open);

var m_readFile2 = new StreamReader(fileStream2);
var m_writeFile2 = new StreamWriter(fileStream2);

        string[] colArr1 = new string[100];
        string[] colArr2 = new string[100];
        string[] colArr3 = new string[100];
        string[] colArr4 = new string[100];
        int arrcount = 1;

        while ((line = m_readFile2.ReadLine()) != null)

        {

            string col1 = "";
            string col2 = "";
            string col3 = "";
            string col4 = "";

                col1 = line.Split('\t')[0];
                col2 = line.Split('\t')[1];
                col3 = line.Split('\t')[2];
                col4 = line.Split('\t')[3];

                colArr1[arrcount] = col1;
                colArr2[arrcount] = col2;
                colArr3[arrcount] = col3;
                colArr4[arrcount] = col4;    


                m_writeFile2.WriteLine("Serv" + arrcount  + "\t" + "25" + "\t" + "400" + "\t" + "High");
                arrcount = arrcount + 1;

【问题讨论】:

    标签: c# string text replace


    【解决方案1】:

    我建议您将这些行拆分为一个数组并重新组合一个新行:

            string source = @"D:\MyFile.txt";
            string destination = @"D:\MyFile2.txt";
    
            int columnToChange = 3;
            string newValueForColumn = "High";
    
            using (FileStream sourceStream = new FileStream(source, FileMode.Open))
            {
                using (FileStream destinationStream = new FileStream(destination, FileMode.CreateNew))
                {
    
                    using (StreamReader sourceReader = new StreamReader(sourceStream))
                    {
    
                        using (StreamWriter destinationWriter = new StreamWriter(destinationStream))
                        {
                            string oldLine = string.Empty;
                            while ((oldLine = sourceReader.ReadLine()) != null)
                            {
                                string[] values = oldLine.Split('\t');
                                StringBuilder newLine = new StringBuilder();
                                if (values.Length > columnToChange)
                                {
                                    values[columnToChange] = newValueForColumn;
                                    for (int i = 0; i < values.Length; i++)
                                    {
                                        newLine.Append(values[i]);
                                        if (i + 1 < values.Length)
                                        {
                                            newLine.Append('\t');
                                        }
                                    }
                                }
                                else
                                {
                                    newLine.Append(oldLine);
                                }
    
                                destinationWriter.WriteLine(newLine.ToString());
                            }
                        }
                    }
                }
            }
    
            // File.Delete(source);
            File.Move(source, source + ".bak");
            File.Move(destination, source);
        }
    

    【讨论】:

    • stringbuilder 是追加字符串的最佳选择
    • 我在数组字符串中构建了完整的新行。它是一个简单的文本文件。但是,当我使用 WriteLine 时,文本文件看起来像这样,没有修改,但添加了额外的行: ServID1 25 800 Low ServID2 25 700 Low ServID3 25 600 LowServID1 25 800 High ServID2 25 700 High 但我希望它修改文本不添加额外的行:-(
    • 真实易懂。当您写回同一个文件时。您应该将所有 newLines 写入一个新文件,完成后您应该关闭这两个文件,删除旧文件并将新文件重命名为旧名称
    • 嗨 Thomas:所以我不能同时读取和修改文本文件!好吧......如果这是真的,那对我来说有点奇怪并且不是自动化的,特别是如果我将修改这个文本文件超过 10 次!我想试试你的建议,介意用关于 ho 的例子指导我删除文件并重命名文本文件....谢谢
    • 我编辑了我的帖子并添加了建议的实现。我还添加了 usings 以在使用后正确处理所有一次性用品。此外,我提取了要替换的列和该列的新值,以便您可以轻松地将其放入方法中。
    【解决方案2】:

    KISS

    string text = File.ReadAllText(route);
    
    text = text.Replace("Low", "High");
    
    File.WriteAllText(route, text);
    

    【讨论】:

    • 我担心这并不能满足所有需求。如果不同的列也包含“低”怎么办。那不应该被取代。我认为你的方法是“简单而愚蠢”;-)
    • @ThomasVoß - 一切都可以......但是,提供的代码完全符合要求。如果要求是其他 - 将有另一个代码。 YAGNI.
    • 感谢您提醒我基本原则。你完全正确。所以现在有两个需求的解决方案......
    【解决方案3】:
        //Works fine Thomas Voß  - I've just added a line to ensure that Column Header is 
        //also not changed
        string source = @"D:\MyFile.txt";
        string destination = @"D:\MyFile2.txt";
    
        int columnToChange = 3;
        string newValueForColumn = "High";
    
        using (FileStream sourceStream = new FileStream(source, FileMode.Open))
        {
            using (FileStream destinationStream = new FileStream(destination, FileMode.CreateNew))
            {
    
                using (StreamReader sourceReader = new StreamReader(sourceStream))
                {
    
                    using (StreamWriter destinationWriter = new StreamWriter(destinationStream))
                    {
                        string oldLine = string.Empty;
                        while ((oldLine = sourceReader.ReadLine()) != null)
                        {
                            string[] values = oldLine.Split('\t');
                            StringBuilder newLine = new StringBuilder();
                            if (values.Length > columnToChange)
                            {
                                if (values[columnToChange] != "ColumnHeaderName")
                                {
                                   values[columnToChange] = newValueForColumn;
                                }
                                for (int i = 0; i < values.Length; i++)
                                {
                                    newLine.Append(values[i]);
                                    if (i + 1 < values.Length)
                                    {
                                        newLine.Append('\t');
                                    }
                                }
                            }
                            else
                            {
                                newLine.Append(oldLine);
                            }
    
                            destinationWriter.WriteLine(newLine.ToString());
                        }
                    }
                }
            }
        }
    
        // File.Delete(source);
        File.Move(source, source + ".bak");
        File.Move(destination, source);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多