我还问的另一个通用平台应用程序问题,还在学习中!
快速问题-我需要使用哪种方法将数据写入文本文件以将字符串追加(而不是覆盖)文本文件?目前,我正在使用异步异步流,但它正在覆盖我的文件。以下是创建和写入文本文件的不同方法:https : //msdn.microsoft.com/zh-cn/library/windows/apps/mt185401.aspx
目前,这是我的代码。是否需要修改以将数据附加到文本文件而不是覆盖它,还是需要使用其他方法之一来附加数据?
//WRITE //Create the text file to hold the data Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile ticketsFile = await storageFolder.CreateFileAsync("tickets.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); //Use stream to write to the file var stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { dataWriter.WriteString("Submitted: " + submitDate + "\n" + "Problem: " + problem + "\n" + "Room: " + location + "\n" + "Description: " + descriptionText.Text + "\n" + "Priority: " + priority + "\n"); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
如果有什么不同,请阅读我的代码:
//READ //Open the text file stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string savedTickets = dataReader.ReadString(numBytesLoaded); textBox.Text = savedTickets; } }
谢谢。
我现在没有可以测试的平台,但这应该可以获取现有文件的长度并将编写器放在末尾(新文件应返回0):
using (var outputStream = stream.GetOutputStreamAt(stream.Size))
除了获取流之外,还可以使用FileIO类。例如方法AppendTextAsync:
await FileIO.AppendTextAsync(ticketsFile, "Submitted: " + submitDate + "\n" + "Problem: " + problem + "\n" + "Room: " + location + "\n" + "Description: " + descriptionText.Text + "\n" + "Priority: " + priority + "\n");