Created
April 23, 2024 09:45
-
-
Save sandrock/c9e504d91a13053bf183739977dc2a20 to your computer and use it in GitHub Desktop.
Writing the content of StringBuilder to a file without calling ToString()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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