简体   繁体   English

如何从FileStream创建TextWriter

[英]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. Newtonsoft.Json需要TextWriter才能创建JsonTextWriter的实例,并且需要由多个类共享。 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. 因此,稍后在编写测试结果时,需要在代码中使用JsonTextWriter实例。

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. 由于可共享性,我需要找到一种打开现有文本文件并将其分配给FileStream并将其放入TextWriter的方法,以便创建我的JsonTextWriter。

But how do I create an instance of the TextWriter using a FileStream? 但是,如何使用FileStream创建TextWriter的实例?

When I try to create a new TextWriter, I get the error that it's an abstract class. 当我尝试创建一个新的TextWriter时,出现错误,它是一个抽象类。

When I try to use File.OpenText(path) I cannot set up the file as FileShare.ReadWrite. 当我尝试使用File.OpenText(path)时,无法将文件设置为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: TextWriter是一个抽象类,您可以使用从其继承的StreamWriter

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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