在挂起或关闭应用程序时从TextBox写入.txt文件

时间:2019-08-02 13:39:47

标签: c# uwp

有一个TextBox,用户可以在其中输入一些数据。关闭应用程序后(通过单击窗口右上方的X按钮),该应用程序需要采用TextBox中键入的任何内容并将其保存到.txt文件,然后再关闭该应用程序。

这是我在App.xaml.cs文件中的代码。

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    //TODO: Save application state and stop any background activity
    await WriteTextToFile();

    deferral.Complete();
}

private async Task WriteTextToFile()
{
    try
    {
        string text = textBox.Text;
        StorageFile textFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///TextFile1.txt"));
        await FileIO.WriteTextAsync(textFile, text);
    }
    catch
    {

    }
}

我在try块的textBox下得到红色下划线。

它说,

  

名称“ textBox”在当前上下文中不存在

我猜想无法从TextBox文件访问App.xaml.cs控件。

1 个答案:

答案 0 :(得分:1)

在App.xaml.cs

    private MainPage mainFrame;
    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame == null)
        {
            rootFrame = new Frame();
            rootFrame.NavigationFailed += OnNavigationFailed;
            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                //TODO: Load state from previously suspended application
            }
            Window.Current.Content = rootFrame;
        }

        if (e.PrelaunchActivated == false)
        {
            if (rootFrame.Content == null)
            {
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
                mainFrame = (MainPage) rootFrame.Content; //*
            }
            Window.Current.Activate();
        }
    }

    private void OnSuspending(object sender, SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();
        string text = mainFrame.Main_TextBox.Text;
        string text2 = MainPage.rootPage.Main_TextBox.Text;
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("hello.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
        await Windows.Storage.FileIO.WriteTextAsync(sampleFile , text);
        deferral.Complete();
    }

在Main.xaml.cs中(TextBox_1 => xaml文件中的TextBox名称)

public sealed partial class MainPage : Page
{
    public TextBox Main_TextBox => TextBox_1; //*
    public static MainPage rootPage; //*
    public MainPage()
    {
        this.InitializeComponent();
        if (rootPage == null)
        {
            rootPage = this;
        }
    }

}

如果文本框位于主框架中,则可以使用App.xaml.cs中的rootFrame访问。您可以通过其他方式在页面中创建静态变量,然后使用任何属性进行访问

编辑:您可以在C:\Users\{UserName}\AppData\Local\Packages\{PackageName}\LocalState\hello.txt

中查看文件