【问题标题】:How can i Append Text Line by line to an existing text file in C#如何将文本逐行附加到 C# 中的现有文本文件
【发布时间】:2017-01-24 17:10:27
【问题描述】:

我有一个包含以下条目的文本文件:

676874463
676844967
676796379
676789975
676760851
676736748

我想读取每个条目并将数据附加到如下:

237676874463#
237676844967#
237676796379#
237676789975#
237676760851#
237676736748#

即,在每个条目的前面附加237,在每个条目的末尾附加#。

到目前为止,这是我的代码:

public class Program
        {
            public string fileDoc = @"c:\Users\UNICS\Desktop\Bulk SMS\BafutFormattedWithoutDuplicates.txt";    
    StreamReader reader = new StreamReader(fileDoc );

     while ((inputline = reader.ReadLine()) != null)
                {
                   // remove duplicates here
                }

谁能指导我如何做到这一点?

【问题讨论】:

  • File.ReadAllLines(),循环和更新,File.WriteAllLines()
  • Oneliner - File.WriteAllLines(path, File.ReadAllLines(path).Select(l => $"237{l}#"));
  • 旁注:对于未来的问题,请展示您尝试过的内容,并避免添加与问题不直接相关的文字(如“欢迎所有答案”)和感谢信(如“干杯”) .我个人不明白为什么你会欢迎所有答案(如果你真的想添加这样的文本,那么你为什么会欢迎所有答案(错误/质量差,一旦这篇文章收集到)而不是要求正确/可理解的答案。

标签: c# io text-files


【解决方案1】:

我正在使用 StringBuilder 并创建一个新文件,在其中保存您想要查看的结果。我是从 BIDS(商业智能开发工作室)做的,但它是 c#,所以它会为你工作。

using System;

using System.IO;
using System.Text;

namespace ST_d1578e806c274e419063843a63f76441.csproj
{
        public void Main()
        {
            String SomeFileName = @"C:\Users\unmsm_02\Desktop\ExampleTextFile.txt"; // Main FILE
            String AuxFileName = @"C:\Users\unmsm_02\Desktop\ResultTextFile.txt"; // File wher eis the result string

            using (FileStream fs = File.Open(SomeFileName, FileMode.Open))
            using (BufferedStream bs = new BufferedStream(fs))
            using (StreamReader sr = new StreamReader(bs))
            {
                String line;
                while (sr.EndOfStream == false)
                {
                    line = sr.ReadLine();
                    if (line.Length > 1)
                    {

                        StringBuilder sb = new StringBuilder();
                        sb.Insert(0, "237");
                        sb.Insert(3, line);
                        sb.Insert(line.Length + 3, "#");

                        String line_Aux = sb.ToString();

                        File.AppendAllText(AuxFileName, line_Aux + "\r\n");
                    }
                }

                Dts.TaskResult = (int)ScriptResults.Success; //FORGET ABOUT THIS, its from the BIDS enviroment, just use the above, and it should work
            }
        }
    }
}

StringBuilder在这里非常有用,您可以使用 Insert 方法创建一个字符串,第一个参数是您要插入的位置,第二个参数是您要插入的字符串。使用完 insert() 后,将其转换为字符串,并在我的情况下将其保存在 line_Aux 上,这是将保存在新文件中的行。

希望对你有帮助!

【讨论】:

    【解决方案2】:

    我想把它读入一个数组并for循环来进行编辑。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace EditText
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Import text from file to an array.
                string[] myArray = File.ReadAllLines("text1.txt");
    
                //This is what will be written into the text file.
                string myFileText = "";
    
                //Loop through the array
                for(int i = 0; i<myArray.Length; i++)
                {
                    //Du the change you want here
                    string myString = "237" + myArray[i] + "#";
    
                    //Add the result to the string you will write to the file
                    myFileText += myString;
                    myFileText += Environment.NewLine;
                }
    
                //Write the text to the file. 
                File.WriteAllText("text1.txt", myFileText);
                //Done
    
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.IO;
      
      namespace ConsoleApplication43
      {
          class Program
          {
              const string IN_FILENAME = @"c:\temp\in.txt";
              const string OUT_FILENAME = @"c:\temp\out.txt";
              static void Main(string[] args)
              {
                  StreamReader reader = new StreamReader(IN_FILENAME);
                  StreamWriter writer = new StreamWriter(OUT_FILENAME);
      
                  string inputline = "";
                  while ((inputline = reader.ReadLine()) != null)
                  {
                      writer.WriteLine("237" + inputline + "#");
                  }
      
                  writer.Flush();
                  writer.Close();
                  reader.Close();
      
              }
          }
      }
      

      【讨论】:

      • 为什么?没有解释,样本在与 OP 所暗示的相同的文件上不起作用,对.Flush() 的毫无意义的调用,使用.Close() 而不是using - 这是什么样的推荐?
      • @Alexei,你的意思是我需要一个实现 IDisposable 的类§
      • @user3015410 我不知道你需要什么。我的评论是关于这个答案中的示例 - 使用 StreamReader(和大多数 System.IO 类)的良好做法是 using(var reader = new StreamReader(IN_FILENAME)) { .... } 而不是 .Close(),由于异常可能会被跳过。
      • 好的@Alexei你的方法现在有意义了。
      猜你喜欢
      • 2021-09-03
      • 2011-01-24
      • 2016-10-23
      • 2010-12-10
      相关资源
      最近更新 更多