简体   繁体   中英

UWP save text in file

I created in XAML 1 BUTTON and 2 TEXTBOXES with names UserInputTextBox and StatusTextBox. Then i created in MainPage.xaml.cs code to open file and save text to file:

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

and if i write to UserInputTextBox text then this text will be in file(.txt) but my problem is if i write to UserInputTextBox text second time, first text will be changed to second text. What i want to do is if i write text to UserInputTextBox so this text must be saved and if i write text there second time, there will be two texts.

You should think about what (Text)files are and how they work. In any case, you're looking to Append text rather than to Overwrite it.

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

Try this and you will see that the results are not separated in anyway. For that you can research the NewLine character(s) or look at AppendLinesAsync() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM