附加到文本文件(不覆盖!)

时间:2015-12-30 23:47:41

标签: c# file append uwp

我的另一个通用平台应用程序问题,仍然在学习!

快速提问 - 我需要使用哪种方法将数据写入文本文件,以便将字符串附加(不覆盖)到文本文件中?目前我使用流使用异步空格但它覆盖了我的文件。以下是创建和写入文本文件的不同方法:https://msdn.microsoft.com/en-us/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;
            }
        }

感谢。

2 个答案:

答案 0 :(得分:5)

我没有在我面前有一个平台我现在可以测试,但是这应该可以获得现有文件的长度并将编写器放在最后(新文件应该返回0):

using (var outputStream = stream.GetOutputStreamAt(stream.Size))

答案 1 :(得分:5)

除了获取流之外,您还可以使用FileIO类。例如,方法 AppendTextAsync

await FileIO.AppendTextAsync(ticketsFile, "Submitted: " + submitDate + "\n" + "Problem: " + problem + "\n" + "Room: " + location + "\n" + "Description: " + descriptionText.Text + "\n" + "Priority: " + priority + "\n");