简体   繁体   中英

How can i show text from a textfile in a textblock? Xaml, BlankApp, Window8

I recently wanted to learn more about fileOpenPickers and decided to make a project. I made a FilOpenPicker. When i choose some textfile from the FileOpenPicker, I wanted to show it in the textblock. But i do not really know how to do that. Further i have a save button and a open button. When I press save it has to save the text from the OpenFilePicker somewhere on my computer. I writed some code, but it is not good at all.

Here is my code:

private async void btnOpen_Click(object sender, RoutedEventArgs e)
{
    FileOpenPicker picker = new FileOpenPicker();
    picker.FileTypeFilter.Add(".log");
    StorageFile result = await picker.PickSingleFileAsync();

    if (result != null)
    {
        try
        {
            await FileIO.WriteTextAsync(result, txtInhoud.Text);
            txtInhoud.Text = result.ToString(); 
        }
        catch (Exception )
        {
            txtInhoud.Text = result.ToString(); 
        }
    }

}

private async void  btnSave_Click(object sender, RoutedEventArgs e)
{
    StorageFolder folder = ApplicationData.Current.RoamingFolder;
    StorageFile file = await folder.CreateFileAsync("MyFolder\\MyFile.txt",
    CreationCollisionOption.ReplaceExisting);
    if (file != null)
    {
        await FileIO.WriteTextAsync(file, "data");
    }
}

I hope you can help me out! I'm sorry for my bad english.

From the way you open the file picker, I assume you are targeting Windows Phone 8.0 Silverlight?

In that case, the FileIO.WriteTextAsync method will not work since it's specific to the WinRT platform. Instead, use the StorageFile.OpenAsync method and pass either Read or ReadWrite as access mode. Both versions will return a stream you can write to / read from.

For example, the code for saving the textbox' content could look as follows:

var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (var writer = new DataWriter(stream.GetOutputStreamAt(0)))
{
    writer.WriteString(txtInhoud.Text);
    await writer.StoreAsync();
    await writer.FlushAsync();
}

For more details (and an example of reading files), see this blog post (sections Write File and Read File )!

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