C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,946 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Example of Text file:
test1
Test2
Test3
Test4
Expectation: I wanted to first remove all double or more blank line and replace them with a single blank line then register the number shown on the last line as a variable.
Test1
Test2
Test3
Test4
Here is the codes I have but am getting an error about cannot convert to string when trying to write out the double + blank lines to a single blank line.
string path = @"C:\Users\LC\Desktop\test.txt";
var lastline = File.ReadLines(path).Last();
// Remove all newlines from the 'example' string variable
lines = Regex.Replace(path, @"^\s+$[\r\n]*", @"\r\n", RegexOptions.Multiline);
File.WriteAllLines(path, lines);
string numbers = Regex.Replace(lastline, "[^0-9]+", string.Empty);
MessageBox.Show(numbers);
Try something like this:
string text = File.ReadAllText( path );
string result = Regex.Replace( text, @"(^\p{Zs}*\r\n){2,}", "\r\n", RegexOptions.Multiline );
File.WriteAllText( path, result );
Note that some text files use different line separators.