How write a file using StreamWriter in Windows 8?

后端 未结 2 634
死守一世寂寞
死守一世寂寞 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:02

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

     private async Task ReadXml(StorageFile xmldata)
        {
            XmlSerializer xmlser = new XmlSerializer(typeof(List));
            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 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>(file);
    

提交回复
热议问题