locked
Unable to create a StreamWriter RRS feed

  • Question

  • The following line of code won't compile:

    StreamWriterwriter = newStreamWriter(filename, false);

    with the error:

    Error 1 The best overloaded method match for 'System.IO.StreamWriter.StreamWriter(System.IO.Stream, System.Text.Encoding)' has some invalid arguments .....

    How do I create a stream so that I can serialize object to a file?

    This code compiles OK in VS2012?

    Wednesday, December 18, 2013 5:44 PM

Answers

  • If you are using metro app you should know that ii doesn't take string as argument any more., 

    Instead of streamwriter you can use something better.

    StorageFolder folder = ApplicationData.Current.LocalFolder;
    StorageFile file = await folder.CreateFileAsync();
    
    using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
        {
            using (DataWriter dataWriter = new DataWriter(outputStream))
            {
                //TODO: Replace "Bytes" with the type you want to write.
                dataWriter.WriteBytes(bytes);
                await dataWriter.StoreAsync();
                dataWriter.DetachStream();
            }
    
            await outputStream.FlushAsync();
        }
    }

    • Marked as answer by Ted Weston Thursday, December 19, 2013 6:40 PM
    Wednesday, December 18, 2013 6:44 PM

All replies

  • If you are using metro app you should know that ii doesn't take string as argument any more., 

    Instead of streamwriter you can use something better.

    StorageFolder folder = ApplicationData.Current.LocalFolder;
    StorageFile file = await folder.CreateFileAsync();
    
    using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
        {
            using (DataWriter dataWriter = new DataWriter(outputStream))
            {
                //TODO: Replace "Bytes" with the type you want to write.
                dataWriter.WriteBytes(bytes);
                await dataWriter.StoreAsync();
                dataWriter.DetachStream();
            }
    
            await outputStream.FlushAsync();
        }
    }

    • Marked as answer by Ted Weston Thursday, December 19, 2013 6:40 PM
    Wednesday, December 18, 2013 6:44 PM
  • Thank you for your prompt reply Rahber, which solves my problem.
    Thursday, December 19, 2013 6:40 PM