Skip to content

Instantly share code, notes, and snippets.

@sandrock
Created April 23, 2024 09:45
Show Gist options
  • Save sandrock/c9e504d91a13053bf183739977dc2a20 to your computer and use it in GitHub Desktop.
Save sandrock/c9e504d91a13053bf183739977dc2a20 to your computer and use it in GitHub Desktop.
Writing the content of StringBuilder to a file without calling ToString()
public static class Utility
{
/// <summary>
/// Buffer-copy the specified StringBuilder contents into a text writer.
/// </summary>
/// <param name="stringBuilder"></param>
/// <param name="stringWriter"></param>
/// <returns></returns>
public static long CopyTo(this StringBuilder stringBuilder, TextWriter stringWriter)
{
// inspired from <https://stackoverflow.com/a/49778464/282105>
// "Writing the content of StringBuilder to a file without calling ToString()"
const int bufferSize = 10000;
char[] buffer = new char[bufferSize];
long total = 0L;
for (int i = 0; i < stringBuilder.Length; i += bufferSize)
{
int count = Math.Min(bufferSize, stringBuilder.Length - i);
stringBuilder.CopyTo(i, buffer, 0, count);
stringWriter.Write(buffer, 0, count);
total += count;
}
return total;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment