2017-02-24 58 views
2

我在XAML 1 BUTTON和2個名爲UserInputTextBox和StatusTextBox的TEXTBOXES中創建。然後,我在MainPage.xaml.cs中的代碼創建,打開文件並保存文本到文件:UWP在文件中保存文本

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文字那麼該文本將在文件(.txt),但我的問題是,如果我第二次寫入UserInputTextBox文本時,第一個文本將被更改爲第二個文本。我想要做的是如果我寫文本到UserInputTextBox,所以這個文本必須保存,如果我第二次寫文本,將有兩個文本。

回答

2

你應該思考什麼(文本)文件以及它們是如何工作的。無論如何,你正在尋找附加文本,而不是覆蓋它。

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

試試這個,你會發現結果在任何情況下都不會分開。爲此,您可以研究NewLine字符或查看AppendLinesAsync()