简体   繁体   中英

How to create a TextWriter from FileStream

Newtonsoft.Json requires a TextWriter in order to create an instance of JsonTextWriter and it needs to be shared by multiple classes. I'm trying to re-use the same results instance for all the tests I decide to run that day.

So, the JsonTextWriter instance needs to be used later on in code when I'm writing the results of my tests.

Because of shareability, I need to figure out a way to open an existing text file and assign it a FileStream and get it into a TextWriter, so I can create my JsonTextWriter.

But how do I create an instance of the TextWriter using a FileStream?

When I try to create a new TextWriter, I get the error that it's an abstract class.

When I try to use File.OpenText(path) I cannot set up the file as FileShare.ReadWrite.

Here is what I have so far:

private void InitializeJSONResultWriter()
{
    string methodName = Utils.getCurrentMethod();
    Log("In:  " + methodName);
    if (textWriter == null)
    {
        //textWriter = File.CreateText(ResultsPath);
        FileStream strm = File.Open(ResultsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        TextWriter textWriter = File.CreateText(ResultsPath);

        // ? ugh

        _jsonTextWriter = new JsonTextWriter(textWriter);
    }
}

TextWriter is an abstract class, you can use StreamWriter that inherits from that:

using (var stream = File.Open("somefile", FileMode.CreateNew))
{
    using (var sw = new StreamWriter(stream))
    {
        using (var jw = new JsonTextWriter(sw))
        {
            jw.WriteRaw("{}");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM