I'm new to C# so I apologize for any trashy code.
I am trying to use StreamWriter.Write/WriteLine to either write a new line or write two consecutive lines as one line to a file.
I have a text file with 12 million rows that has a line break character that occurs in a certain field in hundreds of rows, causing the row to be split into two. Here's a simplified example:
012345, District 1, John Smith, Active\n
987624, District 2\n
, Jane Doe, Inactive\n
583940, District 3, Bobby Roberts, Active\n
I'm using StreamReader and a while loop to read through each line and replace the errant line breaks, then write each line to a new file. I thought I could use Write()
to write the offending line ("987624, District 2") without a line break at the end and WriteLine()
to add the next line to the offending line.
static void Main(string[] args)
{
string line;
using (StreamReader sr = new StreamReader("sourcefile.txt"))
using (StreamWriter swp = new StreamWriter("processedfile.txt", append: true))
{
while ((line = sr.ReadLine()) != null)
{
if (line.Length < 25 && Char.IsDigit(line, 0))
{
swp.Write(line.Replace(Environment.NewLine, ""));
}
else
{
swp.WriteLine(line);
}
}
}
Expected result:
012345, District 1, John Smith, Active
987624, District 2, Jane Doe, Inactive
583940, District 3, Bobby Roberts, Active
Actual result:
012345, District 1, John Smith, Active
987624, District 2
, Jane Doe, Inactive
583940, District 3, Bobby Roberts, Active
I can't do anything about how the file comes, it's just my responsibility to fix it.