Write to a .txt file using data from TextBox when

2019-08-20 17:29发布

问题:

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