【问题标题】:Alternative to File.AppendAllText for newlineFile.AppendAllText 的替代换行符
【发布时间】:2014-09-27 16:29:09
【问题描述】:

我正在尝试从文件中读取字符,然后在删除 cmets(后跟分号)后将它们附加到另一个文件中。

来自父文件的样本数据:

           Name- Harly Brown             ;Name is Harley Brown

           Age- 20                  ;Age is 20 years

想要的结果:

           Name- Harley Brown

           Age- 20

我正在尝试以下代码-

        StreamReader infile = new StreamReader(floc + "G" + line + ".NC0");
        while (infile.Peek() != -1)
        {
            letter = Convert.ToChar(infile.Read());
            if (letter == ';')
            {
                infile.ReadLine();
            }

            else
            {

                System.IO.File.AppendAllText(path, Convert.ToString(letter));

            }
         }

但是我得到的输出是-

            Name- Harley Brown  Age-20

这是因为 AppendAllText 不适用于换行符。有没有其他选择?

【问题讨论】:

    标签: c# file append text-files


    【解决方案1】:

    当然,为什么不使用File.AppendAllLines。请参阅文档here

    向文件追加行,然后关闭文件。如果指定的文件不存在,则该方法创建一个文件,将指定的行写入文件,然后关闭文件。

    它接受任何IEnumerable<string> 并将每一行添加到指定文件中。所以它总是在新行上添加一行。

    小例子:

    const string originalFile = @"D:\Temp\file.txt";
    const string newFile = @"D:\Temp\newFile.txt";
    
    // Retrieve all lines from the file.
    string[] linesFromFile = File.ReadAllLines(originalFile); 
    
    List<string> linesToAppend = new List<string>();
    
    foreach (string line in linesFromFile)
    {
        // 1. Split the line at the semicolon.
        // 2. Take the first index, because the first part is your required result.
        // 3. Trim the trailing and leading spaces.
        string appendAbleLine = line.Split(';').FirstOrDefault().Trim();
    
        // Add the line to the list of lines to append.
        linesToAppend.Add(appendAbleLine);
    }
    
    // Append all lines to the file.
    File.AppendAllLines(newFile, linesToAppend);
    

    输出:

    姓名-哈雷·布朗
    年龄- 20

    如果您更喜欢 LINQ,您甚至可以将 foreach 循环更改为 LINQ 表达式:

    List<string> linesToAppend = linesFromFile.Select(line => line.Split(';').FirstOrDefault().Trim()).ToList();
    

    【讨论】:

    • 感谢您的帮助@Matthijis。但我是一个新手,我将不得不学习一些关于 IEnumerable 的知识。但是在这个例子中,当我正在读取一个完整的文本文件时,附加了两条不同的行,然后期望程序读取“\r\n”并自动添加一个换行符。我应该读取父级中的每一行吗文件然后写..??
    【解决方案2】:

    您可以使用 LINQ、System.File.ReadLines(string)System.File.WriteAllLines(string, IEnumerable&lt;string&gt;) 执行此操作。如果这实际上是您想要的功能,您也可以以查找和替换方式使用System.File.AppendAllLines(string, IEnumerable&lt;string&gt;)。顾名思义,区别在于它是将所有内容作为新文件写出,还是只是附加到现有文件。

    System.IO.File.WriteAllLines(newPath, System.IO.File.ReadLines(oldPath).Select(c =>
                       {
                           int semicolon = c.IndexOf(';');
    
                           if (semicolon > -1)
                               return c.Remove(semicolon);
                           else
                               return c;
                       }));
    

    如果您对 LINQ 语法不太熟悉,这里的想法是遍历文件中的每一行,如果它包含分号(即,IndexOf 返回大于 -1 的内容)我们切断它,否则,我们只返回字符串。然后我们将所有这些写入文件。与此等效的 StreamReader 将是:

    using (StreamReader reader = new StreamReader(oldPath))
    using (StreamWriter writer = new StreamWriter(newPath))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
           int semicolon = line.IndexOf(';');
    
           if (semicolon > -1)
               line = c.Remove(semicolon);
    
           writer.WriteLine(line);
        }
    }
    

    虽然,当然,这会在末尾提供一个额外的空行,而 LINQ 版本不会(据我所知,我突然想到我对此不是百分百确定,但如果阅读本文的人确实知道我会很感激您的评论)。

    另一件重要的事情要注意,看看你的原始文件,你可能想添加一些Trim 调用,因为看起来你的分号前可以有空格,我不认为你想要那些被复制的通过。

    【讨论】:

      【解决方案3】:

      当 .NET Framework 充满了有用的字符串操作函数时,为什么还要使用逐字符比较?

      另外,一个文件写入功能只能使用一次,不要多次使用,太费时间和资源了!

      StreamReader stream = new StreamReader("file1.txt");
      string       str    = "";
      
      while ((string line = infile.ReadLine()) != null) { // Get every line of the file.
          line = line.Split(';')[0].Trim();               // Remove comment (right part of ;) and useless white characters.
          str += line + "\n";                             // Add it to our final file contents.
      }
      
      File.WriteAllText("file2.txt", str); // Write it to the new file.
      

      【讨论】:

      • Environment.NewLine怎么样
      • @Zigma +1。特别是因为我们使用 C# 在 Windows 机器上工作,所以换行符实际上是回车后跟换行符 (\r\n),而不仅仅是换行符。
      • @Xatrix。非常感谢,我不知道 .split 和 .trim 命令。但不幸的是结果还是一样..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      相关资源
      最近更新 更多