簡體   English   中英

UWP將文本保存在文件中

[英]UWP save text in file

我在XAML中創建了1個按鈕和2個文本框,名稱分別為UserInputTextBox和StatusTextBox。 然后我在MainPage.xaml.cs代碼中創建了打開文件並將文本保存到文件的方法:

FileOpenPicker picker = new FileOpenPicker();       
private async void Button_Click(object sender, RoutedEventArgs e)
{

    // Set properties on the file picker such as start location and the type 
    // of files to display.
    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    picker.ViewMode = PickerViewMode.List;
    picker.FileTypeFilter.Add(".txt");

    // Show picker enabling user to pick one file.
    StorageFile result = await picker.PickSingleFileAsync();

    if (result != null)
    {
        try
        {
            // Use FileIO to replace the content of the text file
            await FileIO.WriteTextAsync(result, UserInputTextBox.Text);

            // Display a success message
            StatusTextBox.Text = "Status: File saved successfully";
        }
        catch (Exception ex)
        {
            // Display an error message
            StatusTextBox.Text = "Status: error saving the file - " + ex.Message;
        }
    }
    else
        StatusTextBox.Text = "Status: User cancelled save operation";
}

如果我寫入UserInputTextBox文本,那么此文本將位於file(.txt)中,但是我的問題是,如果我第二次寫入UserInputTextBox文本,則第一個文本將更改為第二個文本。 我想做的是,如果我向UserInputTextBox中寫入文本,則必須保存此文本,如果我第二次在此處寫入文本,將有兩個文本。

您應該考慮什么是(文本)文件以及它們如何工作。 無論如何,您都希望添加文本而不是覆蓋文本。

 //await FileIO.WriteTextAsync(result, UserInputTextBox.Text);
   await FileIO.AppendTextAsync(result, UserInputTextBox.Text);

嘗試此操作,您將發現結果始終沒有分開。 為此,您可以研究NewLine字符或查看AppendLinesAsync()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM