I have a requirement to write HTML to the file system and I was wondering if there is any speed boost in converting it to bytes and writing it using a FileStream rather than using the File.WriteAllText() (or a similar text method).
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
File.WriteAllText uses a StreamWriter behind the scenes:
You have a string already, so converting it to a byte array would be pointless, because this is performed inside the StreamWriter.Flush method anyway using its underlying Encoder class. Flush is called by the StreamWriter.Dispose method which the using clause calls. This is a snippet from the source of Flush via reflector:
You can see it has a charBuffer. That’s just a char[] array which it writes to when you perform StreamWriter.Write(string).
So in short, you already have the string, just let the shorter File method perform the cascading calls, as it makes your source slightly more readable. Converting it to a byte array is also not necessary, as I mentioned the StreamWriter does it for you.
If you’re getting conversion issues then use Encoding.Unicode as the final parameter in the 3 parameter overload, as File.WriteAllText(string,string) uses UTF8 without a BOM.