I’m trying to convert one value to another. I am importing a text file, using streamreader/writer. I want to know if I can have the part of the while loop inside the if statement wait until the the rest of the loop finishes before writing what its supposed to. I know this is probably an easy question but for some reason I can put my finger on it. I am not using multithread processing and want to stay away from asynch.
using (StreamReader reader = new StreamReader(convertInput))
{
string line;
writer.WriteLine(formatter, "Original Value", "Converted Value");
writer.WriteLine(formatter, "--------------", "---------------");
A: while ((line = reader.ReadLine()) != null)
{
string str2BeConverted = line;
long numHexToDex;
if ((Int64.TryParse(line, NumberStyles.HexNumber, null, out numHexToDec)) == false)
{
writer.WriteLine();
writer.Write(line + " " + "is not a Hexadecimal value.");
goto A;
}
Int64.TryParse(line, NumberStyles.HexNumber, null, out numHexToDec);
string lineChanged = numHexToDec.ToString("G");
}
}
I am wanting to wait until all the values that parse successfully are written, then write the ones that didn’t at the end.
The easiest way is to write these to some sort of buffer instead, such as a StringBuilder, and then write the StringBuilder’s contents out after all the successful elements were processed:
Also, as many comments have stated, code that uses
gotois NEVER good code. There is ALWAYS something else you could do that is more correct, and in this case it’s extremely simple (thecontinuekeyword will bypass the rest of the loop block, re-evaluate the while condition, and iterate further if indicated).