Write to a .txt file using data from TextBox when UWP app is closed

耗尽温柔 提交于 2019-12-24 18:26:16

问题


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.

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
        {

        }
    }

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;
            }
        }
}

回答1:


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.

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



来源:https://stackoverflow.com/questions/57336035/write-to-a-txt-file-using-data-from-textbox-when-uwp-app-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!