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