简体   繁体   中英

How write a file using StreamWriter in Windows 8?

I'm having trouble when creating a StreamWriter object in windows-8, usually I just create an instance just passing a string as a parameter, but in Windows 8 I get an error that indicates that it should recieve a Stream, but I noticed that Stream is an abstract class, Does anybody knows how will be the code to write an xml file?, BTW I'm using .xml because I want to save the serialized object, or does anyone knows how to save to a file a serialized object in Windows 8?.

Any ideas?

Currently using Windows 8 Consumer Preview

Code:

StreamWriter sw = new StreamWriter("person.xml");

Error:

The best overloaded method match for 'System.IO.StreamWriter.StreamWriter(System.IO.Stream)' has some invalid arguments

Instead of StreamWriter you would use something like this:

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();
    }
}

You can look at the StringIOExtensions class in the WinRTXamlToolkit library for sample use.

EDIT*

While all the above should work - they were written before the FileIO class became available in WinRT, which simplifies most of the common scenarios that the above solution solves since you can now just call await FileIO.WriteTextAsync(file, contents) to write text into file and there are also similar methods to read, write or append strings, bytes, lists of strings or IBuffers .

You can create a common static method which you can use through out application like this

 private async Task<T> ReadXml<T>(StorageFile xmldata)
    {
        XmlSerializer xmlser = new XmlSerializer(typeof(List<myclass>));
        T data;
        using (var strm = await xmldata.OpenStreamForReadAsync())
        {
            TextReader Reader = new StreamReader(strm);
            data = (T)xmlser.Deserialize(Reader);
        }
        return data;
    }

    private async Task writeXml<T>(T Data, StorageFile file)
    {
        try
        {
            StringWriter sw = new StringWriter();
            XmlSerializer xmlser = new XmlSerializer(typeof(T));
            xmlser.Serialize(sw, Data);

            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
                {
                    using (DataWriter dataWriter = new DataWriter(outputStream))
                    {
                        dataWriter.WriteString(sw.ToString());
                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outputStream.FlushAsync();
                }
            }


        }
        catch (Exception e)
        {
            throw new NotImplementedException(e.Message.ToString());

        }

    }

to write xml simply use

 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("data.xml",CreationCollisionOption.ReplaceExisting);
        await  writeXml(Data,file);

and to read xml use

  StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.xml");
      Data =  await  ReadXml<List<myclass>>(file);

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