UWP在文件中保存文本
问题描述:
我在XAML 1 BUTTON和2个名为UserInputTextBox和StatusTextBox的TEXTBOXES中创建。然后,我在MainPage.xaml.cs中的代码创建,打开文件并保存文本到文件:UWP在文件中保存文本
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,所以这个文本必须保存,如果我第二次写文本,将有两个文本。
答
你应该思考什么(文本)文件以及它们是如何工作的。无论如何,你正在寻找附加文本,而不是覆盖它。
//await FileIO.WriteTextAsync(result, UserInputTextBox.Text);
await FileIO.AppendTextAsync(result, UserInputTextBox.Text);
试试这个,你会发现结果在任何情况下都不会分开。为此,您可以研究NewLine字符或查看AppendLinesAsync()
。