Search code examples
asp.netconstructor.net-corevisual-studio-2017streamwriter

System.IO.StreamWriter has no string constructor in .netcore 1.1


I'm taking my first baby steps in .NET Core V1.1 under VS2017 community edition.

I ported some chunks of code to an ASP.NET Core project that utilizes System.IO.StreamWriter:

string fileName = "Hello_world.txt";

using (StreamWriter file = new StreamWriter(fileName))
{   
    // do stuff...
}

With this I get a compiler error:

error CS1503: Argument 1: cannot convert from 'string' to 'System.IO.Stream'

On the other hand the .NET API doc clearly states that a constructor with string is available, see here.

Can anybody tell me why there is no constructor that receives a string and where to find the correct API doc?


Solution

  • The StreamWriter constructors taking string arguments will only be available in .NET Core 2.0 and higher. You can look up the availability at https://apisof.net/catalog/System.IO.StreamWriter..ctor(String)

    In the meantime, you can create a FileStream, which is exactly what the constructor taking a string does.

        string path = "foo.txt";
        using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan))
        using (var streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8, 1024, false))
        {
            streamWriter.WriteLine("hey");
        }