Somebody Somebody - 2 months ago 12
C# Question

Best way to remove the very last carriage return in StreamWriter.WriteLine c#

I have bellow code:

SqlDataReader Rdr = Cmd.ExecuteReader();
if (Rdr.HasRows)
{
using (StreamWriter writer = new StreamWriter("c:\\Test.txt"))
{
while (Rdr.Read())
{
writer.WriteLine(Rdr["Item1"].ToString() + Rdr["Item2"].ToString());
}
}
}
Rdr.Close();


WriteLine
adds a carriage return every time, but I need to avoid that when the last line is reached.

I found bellow code to know when the SqlDataReader is in the last line, where at that point I can change the
WriteLine
by
Write
which does not add the carriage return:

if (reader.HasRows)
{
var loop = true;
while (loop)
{
//1. Here retrive values you need e.g. var myvar = reader.GetBoolean(0);
loop = reader.Read();
if (!loop)
{
//You are on the last record. Use values read in 1.
//Do some exceptions
}
else {
//You are not on the last record.
//Process values read in 1., e.g. myvar
}
}
}


Any other idea to do this in a better way?

Answer

It can be achieved with simple flag and separate Write / WriteLine:

bool first = true;
while (Rdr.Read())
{
    if (!first) writer.WriteLine();
    writer.Write(Rdr["Item1"].ToString() + Rdr["Item2"].ToString());
    first = false;
}
Comments