How do I pass an IFormatProvider to a StreamWriter?
Specifically I want to create anew StreamWriter("myfile.txt", CultureInfo.InvariantCulture);
TextWriter and StringWriter have a parameter for that in the constructor, but StreamWriter does not.
The Property stringWriter.FormatProvider is readonly.
I could think of three workarounds that seem like bad solutions:
Is there any way to specify a FormatProvider for StreamWriter? Based on Inheritance from TextWriter, the StreamWriter must have the means to handle this, if I could just set the property.
Since the FormatProvider
property is virtual you can create your own subclass which takes an IFormatProvider
:
public class FormattingStreamWriter : StreamWriter
{
private readonly IFormatProvider formatProvider;
public FormattingStreamWriter(string path, IFormatProvider formatProvider)
: base(path)
{
this.formatProvider = formatProvider;
}
public override IFormatProvider FormatProvider
{
get
{
return this.formatProvider;
}
}
}
You could create a new class inheriting from StreamWriter and override the virtual FormatProvider property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With