在 UWP 应用程序关闭时使用来自 TextBox 的数据写入 .txt 文件 [英] Write to a .txt file using data from TextBox when UWP app is closed
问题描述
当用户关闭应用程序时,我相信 App.xaml.cs 中的 OnSuspending 方法在终止之前首先被调用.因此,我将代码放在那里,以便自动将用户在 TextBox 中写入的内容保存到名为 TextFile1.txt 的 .txt 文件中.程序运行时没有错误,但当应用程序关闭时,它不会将用户的数据保存到 .txt 文件中.
When user closes the app, I believe the OnSuspending method in App.xaml.cs is called first before termination. So, I put my code in there in order to automatically save what the user wrote in the TextBox to a .txt file called TextFile1.txt. The program runs without errors but it doesn't save the user's data to the .txt file when app is closed.
App.xaml.cs 中的代码:
Code in App.xaml.cs:
private MainPage mainFrame;
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
await WriteTextToFile();
deferral.Complete();
}
private async Task WriteTextToFile()
{
try
{
string text = mainFrame.mainTextBox.Text;
StorageFile textFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///TextFile1.txt"));
await FileIO.WriteTextAsync(textFile, text);
}
catch
{
}
}
MainPage.xaml.cs 中的代码:
Code in MainPage.xaml.cs:
public sealed partial class MainPage : Page
{
public TextBox mainTextBox => textBox;
public static MainPage rootPage;
public MainPage()
{
InitializeComponent();
if (rootPage != null)
{
rootPage = this;
}
}
}
推荐答案
您的代码失败,因为它尝试写入应用程序的安装文件夹.此文件夹受到保护以确保安装的完整性.
Your code fails because it attempts to write to the app's installation folder. This folder is protected to ensure the integrity of the installation.
要使您的方案发挥作用,请将文本文件写入您的 AppData 位置.https://docs.microsoft.com/en-us/windows/uwp/design/app-settings/store-and-retrieve-app-data
To make your scenario work, write the text file to your AppData location instead. https://docs.microsoft.com/en-us/windows/uwp/design/app-settings/store-and-retrieve-app-data
这篇关于在 UWP 应用程序关闭时使用来自 TextBox 的数据写入 .txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!