How to save the contents of a string to a text file in Windows 8 / Windows Runtime?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    How to save the contents of a string to a text file in Windows 8 / Windows Runtime?

    Note: These examples are in Visual Basic, but the use case is the same for C# with the Windows Runtime.

    To save files to a user's computer, use the FileIO class that is part of the Windows.Storage class namespace. It's as simple importing the Windows.Storage namespace (in Visual Basic, this would be at the very top of the code-behind file with Imports Windows.Storage) and saving the file using Await FileIO.WriteTextAsync(FilePath, String).

    The first argument in the WriteTextAsync() method (i.e. the FilePath) requires a StorageFile object. For example:

    Dim file As StorageFile = Await StorageFile.GetFileFromPathAsync("../path_string")

    For more information on the Await operator, see the msdn documentation. Short answer in the msdn is, "the Await operator [is to] suspend execution of the method until the awaited task completes".

    Note: If you use the Await operator, you must make your method or subroutine an asynchronous method using the async operator, like:

    Code:
    [B]Private [U]Async[/U] Sub ShowSaveFilePicker()[/B]
            Dim TextBoxText As String = ""
    
            If Me.ActiveFile IsNot Nothing Then
                TextBox.Document.GetText(Windows.UI.Text.TextGetOptions.UseCrlf, TextBoxText)
                Await FileIO.WriteTextAsync(Me.ActiveFile, TextBoxText)
            Else
                Dim SavePicker As New FileSavePicker
    
                SavePicker.FileTypeChoices.Add("Text File", New List(Of String) From {".txt"})
                SavePicker.FileTypeChoices.Add("Word File", New List(Of String) From {".docx"})
    
                Dim FileSaved As StorageFile = Await SavePicker.PickSaveFileAsync()
    
                If FileSaved IsNot Nothing Then
                    TextBox.Document.GetText(Windows.UI.Text.TextGetOptions.UseCrlf, TextBoxText)
                    Await FileIO.WriteTextAsync(FileSaved, TextBoxText)
                End If
    
                Dim file As StorageFile = Await StorageFile.GetFileFromPathAsync("../path")
            End If
        End Sub
Working...
X