Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter and IFormatProvider

How do I pass an IFormatProvider to a StreamWriter?

Specifically I want to create a
new 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:

  • Changing Thread.CurrentCulture: This is going to be in a library, so I'd rather not change any global settings, even temporarily.
  • sw.WriteLine(InvariantCulture, , ): There are a lot of sw.WriteLine() over several functions. I'd really like to avoid messing with all of them.
  • using a StringWriter first and then writing the string to a file: since the stream can get very big, this will incur a huge overhead.

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.

like image 842
HugoRune Avatar asked Aug 17 '12 19:08

HugoRune


2 Answers

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;
        }
    }
}
like image 152
Lee Avatar answered Oct 12 '22 11:10

Lee


You could create a new class inheriting from StreamWriter and override the virtual FormatProvider property.

like image 32
Scott Avatar answered Oct 12 '22 10:10

Scott