c# - 组合框使用不可见的换行符 (\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,我将非常感激。谢谢。
解决方案
我的方法
// 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
推荐阅读
- websphere - 在 IBM MQ Advanced for Developers 中可以实现的每个实例的最大吞吐量是多少?
- css -
Bootstrap 5 上的标签有不同的颜色? - apache-camel - JMS 组件中的 exchangePattern 是仅消费者参数还是通用(消费者和生产者)?
- assembly - 尝试比较 8086 中的字符串时出现错误
- excel - Excel 按列名而不是偏移量引用表格单元格
- typo3 - Typo3 10+ 中后端布局名称的条件
- .htaccess - 使用 .htaccess 重写 url 名称
- c++ - 在 cmake 中覆盖 add_library() 时 find_package 出错
- database - 如何将数据分离到不同的数据库中?
- r - filter() 在 For 循环中不起作用的解决方案?