【问题标题】:Combobox loading text with invisible linefeed (\r) or newline (\n)组合框使用不可见的换行符 (\r) 或换行符 (\n) 加载文本
【发布时间】:2018-05-25 15:52:02
【问题描述】:

我正在使用 c#、visual studio 2017、winforms 和 我遇到了一个组合框的问题,该组合框正在从文本文件中加载一些文本,当我从组合框中选择另一行文本时,会在其中添加换行符(\r),看起来它有点不可见或更好的说法, 它看起来像一个换行符 (\n)。

这是有问题的组合框和不可见的换行符 (\r)。 https://i.stack.imgur.com/Xhymg.png

当我调试应用程序时,我可以看到在该行文本之后添加了 \r。 https://i.stack.imgur.com/km4F3.png

我尝试在保存文本时使用 Encoding.Unicode,但无济于事。

//This is how I save text to a file
private void SaveVarNameToFile()
{
    using (var writer = File.AppendText("savedVarName.txt"))
    {
        writer.Write(comboBox1.Text, Encoding.Unicode);
    }
}

//This is how I load the text to combobox
private void LoadStrTextFromFile(string fileName, ComboBox cb)
{
   if (!File.Exists(fileName))
            return;

   using (StreamReader reader = new StreamReader(fileName))
   {
      string x = reader.ReadToEnd();
      string[] y = x.Split('\n');
      foreach (string s in y)
      {
         cb.Items.Add(s);
      }
      reader.Close();
    }
}

文本文件的内容:

BOOST_ROOT
NUMBER_OF_PROCESSORS
OS
PROCESSOR_LEVEL

我很难弄清楚如何移除那个讨厌的小东西。也许有一个简单的解决方法。 如果有人可以帮助我找到一种方法或删除它或修改代码使其不会加载 \r,我将非常感激。谢谢。

【问题讨论】:

  • 你可以使用File.ReadLines(filename)foreach (var line in File.ReadLines(filename)) cb.Items.Add(line);
  • 请添加文本文件的内容

标签: c# windows winforms combobox visual-studio-2017


【解决方案1】:

Windows 使用 \r\n 来标记一行文本的结尾。 *NIX 和 Mac 使用不同的标记。你可以看到不同的系统如何处理这个here

我建议不要手动处理行拆分,而是使用内置功能来执行此操作(即File.ReadLines()):

private void LoadStrTextFromFile(string fileName, ComboBox cb)
{
    if (!File.Exists(fileName))
        return;

    foreach (string line in File.ReadLines(fileName))
        cb.Items.Add(line);
}

【讨论】:

    【解决方案2】:

    我的方法

        // remember to use double back slash on the path
        string[] text  = System.IO.File.ReadAllLines("C:\\test.txt").Where(line => !string.IsNullOrWhiteSpace(line)).Distinct().ToArray(); // read the file into a string array with removing the duplicates and empty lines
        comboBox1.Items.AddRange(text); // finally fill in the combobox with the array
    

    【讨论】:

    • 感谢您分享您的做法。我会试试的。
    猜你喜欢
    • 2019-02-17
    • 2013-12-02
    • 2020-10-26
    • 2011-08-22
    • 2015-09-22
    • 2012-08-03
    • 2010-12-20
    • 1970-01-01
    相关资源
    最近更新 更多