I am using StringBuilder
to format my string values like below
Student Number: 3602
Registered On: 9/11/2018 12:00:00 AM
Enrollment number: 0
but when I am writing this to a text file using below code
using (StreamWriter sw = new StreamWriter(@"LocaltempPath\Sheet.txt"))
{
sw.WriteLine(sb.ToString());
}
my entire formatting is getting missed, instead of above shown format, values gets copied in one line of text file! How to preserve format while writing to text file?
Update : My StringBuilder code
StringBuilder sb = new StringBuilder("Student Number: " + StId);
sb.Append("\n");
sb.Append("Registered On: " + regdate);
sb.Append("\n");
sb.Append("Enrollment No: " + regnumber);
sb.Append("\n");
As per the comments, don't use hardcoded "\n" to mean newline, unless you're preparing data for a unix system
Do this instead:
StringBuilder sb = new StringBuilder("Student Number: " + StId);
sb.AppendLine();
sb.AppendLine("Registered On: " + regdate);
sb.AppendLine("Enrollment No: " + regnumber);
AppendLine() can be used without any arguments to just put a newline in, and I do this above to put a new line on the end of the string that you created the stringbuilder with. Could also have done this:
StringBuilder sb = new StringBuilder();
sb.AppendLine("Student Number: " + StId);
sb.AppendLine("Registered On: " + regdate);
sb.AppendLine("Enrollment No: " + regnumber);
If you want more control over the format of the dates etc:
StringBuilder sb = new StringBuilder();
sb.AppendLine("Student Number: " + StId);
sb.AppendFormat("Registered On: {0:yyyy-MM-dd HH:mm:ss.fff}\r\n", regdate);
sb.AppendLine("Enrollment No: " + regnumber);
Finally, every call to AppendXXX() on a stringbuilder returns the same stringbuilder, so you can call like this and save some typing:
StringBuilder sb = new StringBuilder();
sb.Append("Student Number: ").AppendLine(StId)
.Append("Registered On: ").AppendLine(regdate);
.Append("Enrollment No: ").AppendLine(regnumber);
Really, you should avoid mixing string concatenation with + and stringbuilder - it's more efficient if you're doing a lot of stringbuilding to just use the stringbuilder. It might not make your code more readable though
In terms of readable code, you might also like to know that you can do this:
StringBuilder sb = new StringBuilder();
sb.AppendLine($"Student Number: {StId}");
sb.AppendLine($"Registered On: {regdate}");
sb.AppendLine($"Enrollment No: {regnumber}");
In this trivial example it doesnt help much, but it can really help with strings that concatenate a lot of stuff:
$"Student Number: {StId}, Registered On: {regdate}, Enrollment No: {regnumber}"
//instead of
"Student Number: " + StId + ", Registered On: " + regdate + ", Enrollment No: " + regnumber