How write a file using StreamWriter in Windows 8?

后端 未结 2 644
死守一世寂寞
死守一世寂寞 2020-12-01 12:47

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

2条回答
  •  感动是毒
    2020-12-01 13:05

    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.

提交回复
热议问题