[英]UWP save text in file
我在XAML中创建了1个按钮和2个文本框,名称分别为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文本,那么此文本将位于file(.txt)中,但是我的问题是,如果我第二次写入UserInputTextBox文本,则第一个文本将更改为第二个文本。 我想做的是,如果我向UserInputTextBox中写入文本,则必须保存此文本,如果我第二次在此处写入文本,将有两个文本。
您应该考虑什么是(文本)文件以及它们如何工作。 无论如何,您都希望添加文本而不是覆盖文本。
//await FileIO.WriteTextAsync(result, UserInputTextBox.Text);
await FileIO.AppendTextAsync(result, UserInputTextBox.Text);
尝试此操作,您将发现结果始终没有分开。 为此,您可以研究NewLine字符或查看AppendLinesAsync()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.