首页 > 解决方案 > 组合框使用不可见的换行符 (\r) 或换行符 (\n) 加载文本

问题描述

我正在使用 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,我将非常感激。谢谢。

标签: c#windowswinformscomboboxvisual-studio-2017

解决方案


我的方法

    // 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

推荐阅读