当 UWP 应用程序关闭时,使用来自 TextBox 的数据写入 .txt 文件

考试

当用户关闭应用程序时,我相信 App.xaml.cs 中的 OnSuspending 方法在终止之前首先被调用。因此,我将代码放在那里,以便自动将用户在 TextBox 中写入的内容保存到名为 TextFile1.txt 的 .txt 文件中。该程序运行时没有错误,但当应用程序关闭时,它不会将用户的数据保存到 .txt 文件中。

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 中的代码

public sealed partial class MainPage : Page
{
        public TextBox mainTextBox => textBox;
        public static MainPage rootPage;
        public MainPage()
        {
            InitializeComponent();
            if (rootPage != null)
            {
                rootPage = this;
            }
        }
}
斯特凡威克 MSFT

您的代码失败,因为它尝试写入应用程序的安装文件夹。此文件夹受到保护以确保安装的完整性。

要使您的方案工作,请将文本文件写入您的 AppData 位置。https://docs.microsoft.com/en-us/windows/uwp/design/app-settings/store-and-retrieve-app-data

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章