UWP将文本保存在文件中

时间:2017-02-24 10:25:39

标签: c# xaml file-io uwp

我在XAML 1 BUTTON和2个TEXTBOXES中创建了名称UserInputTextBox和StatusTextBox。然后我在MainPage.xaml.cs代码中创建了打开文件并将文本保存到文件:

FileOpenPicker picker = new FileOpenPicker();       
private async void Button_Click(object sender, RoutedEventArgs e)
{

    // Set properties on the file picker such as start location and the type 
    // of files to display.
    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    picker.ViewMode = PickerViewMode.List;
    picker.FileTypeFilter.Add(".txt");

    // Show picker enabling user to pick one file.
    StorageFile result = await picker.PickSingleFileAsync();

    if (result != null)
    {
        try
        {
            // Use FileIO to replace the content of the text file
            await FileIO.WriteTextAsync(result, UserInputTextBox.Text);

            // Display a success message
            StatusTextBox.Text = "Status: File saved successfully";
        }
        catch (Exception ex)
        {
            // Display an error message
            StatusTextBox.Text = "Status: error saving the file - " + ex.Message;
        }
    }
    else
        StatusTextBox.Text = "Status: User cancelled save operation";
}

如果我写入UserInputTextBox文本,那么这个文本将在文件(.txt)中,但我的问题是如果我第二次写入UserInputTextBox文本,第一个文本将被更改为第二个文本。我想要做的是,如果我写文本到UserInputTextBox所以这个文本必须保存,如果我第二次写文本,将有两个文本。

1 个答案:

答案 0 :(得分:2)

你应该考虑一下(文本)文件是什么以及它们是如何工作的。在任何情况下,您都希望附加文本而不是覆盖它。

 //await FileIO.WriteTextAsync(result, UserInputTextBox.Text);
   await FileIO.AppendTextAsync(result, UserInputTextBox.Text);

试试这个,你会发现结果没有分开。为此,您可以研究NewLine角色或查看AppendLinesAsync()