How to remove empty lines in a string in C#? I am generating some text files in C# (winforms) and for some reason there are some empty lines. How can I remove them after the
I found simple answer to this problem
YourradTextBox.Lines = YourradTextBox.Lines.Where(p => p.Length > 0).ToArray();
Adapted from Marco Minerva [MCPD] at: https://social.msdn.microsoft.com/Forums/windows/en-US/b1bb4107-4ad5-4cd3-bd20-9c2b3f9b31a6/delete-lines-from-multiline-textbox-if-its-contain-certain-string-c?forum=winforms&prof=required
@Tim Pietzcker - Not working for me. I have to change a little bit but thx!
Ehhh C# Regex.. I had to change it again but this working good:
private string RemoveEmptyLines(string lines)
{
return Regex.Replace(lines, @"^\s*$\n|\r", string.Empty, RegexOptions.Multiline).TrimEnd();
}
Example: http://regex101.com/r/vE5mP1/2
No method mentioned here helped me all the way, but I found a workaround.
{}
public static IEnumerable<string> SplitToLines(this string inputText, bool removeEmptyLines = true)
{
if (inputText == null)
{
yield break;
}
using (StringReader reader = new StringReader(inputText))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (removeEmptyLines && !string.IsNullOrWhiteSpace(line))
yield return line.Trim();
else
yield return line.Trim();
}
}
}
public static string ToMultilineText(this string text)
{
var lines = text.SplitToLines();
return string.Join(Environment.NewLine, lines);
}
You could try String.Replace("\n\n", "\n");
private string remove_space(string st)
{
String final = "";
char[] b = new char[] { '\r', '\n' };
String[] lines = st.Split(b, StringSplitOptions.RemoveEmptyEntries);
foreach (String s in lines)
{
if (!String.IsNullOrWhiteSpace(s))
{
final += s;
final += Environment.NewLine;
}
}
return final;
}