I'm using c#, visual studio 2017, winforms and I'm having a problem with a combobox which is loading some text from a text file and when I select another line of text from the combobox, a linefeed (\\r) is added there, and it looks like it's somewhat invisible or better saying, it looks like a newline (\\n).
This is the combobox in question and the invisible linefeed (\\r). https://i.stack.imgur.com/Xhymg.png
When I debug the application I can see \\r added after that line of text. https://i.stack.imgur.com/km4F3.png
I've tried to use Encoding.Unicode when saving the text, but to no avail.
//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();
}
}
Contents of the text file:
BOOST_ROOT
NUMBER_OF_PROCESSORS
OS
PROCESSOR_LEVEL
I'm having a hard time figuring out how to remove that pesky little thing. Perhaps there's an easy fix. If someone can help me find a way or remove it or modify the code so it won't load the \\r, I would be very grateful. Thanks.
Windows uses \\r\\n to mark the end of a line of text. *NIX and Macs use different markers. You can see how different systems handle this here .
Instead of handling the splitting of lines manually, I recommend using built-in functionality for doing this (ie 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);
}
My approach
// 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.