09 April 2017

Windows Store và File: Tạo Lưu Đọc File Async trên Windows Store C#

MainPage.xaml
Windows Store 2017
<Page
    x:Class="Theory2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Theory2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button x:Name="btnCreateFile" Content="Create File" HorizontalAlignment="Left" Margin="273,173,0,0" VerticalAlignment="Top" Height="42" Width="174" Click="btnCreateFile_Click"/>
        <Button x:Name="btnReadFile" Content="Read File" HorizontalAlignment="Left" Margin="470,173,0,0" VerticalAlignment="Top" Height="42" Width="174" Click="btnReadFile_Click"/>
        <Button x:Name="btnDeleteFile" Content="Delete File" HorizontalAlignment="Left" Margin="671,173,0,0" VerticalAlignment="Top" Height="42" Width="174" Click="btnDeleteFile_Click"/>
        <TextBlock x:Name="tbMessage" FontSize="24" HorizontalAlignment="Left" Margin="276,256,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"/>
        <TextBox x:Name="txtMessage" HorizontalAlignment="Left" Margin="276,325,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="135" Width="566"/>
        <Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" Margin="533,501,0,0" VerticalAlignment="Top" Click="btnSave_Click"/>

    </Grid>
</Page>
MainPage.xaml.cs
Windows Store 2017
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace Theory2
{

    public sealed partial class MainPage : Page
    {
        StorageFile sf = null;
        string fileName = "test.txt";
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void btnCreateFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFolder folder = ApplicationData.Current.LocalFolder;
                //txtMessage.Text = folder.Path;
                sf = await folder.CreateFileAsync(fileName, CreationCollisionOption.FailIfExists);
                tbMessage.Text = folder.Path;

            }
            catch (Exception ex)
            {
                tbMessage.Text = "Error: " + ex.Message;
            }

        }

        private async void btnReadFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFolder sFolder = ApplicationData.Current.LocalFolder;
                sf = await sFolder.GetFileAsync(fileName);
                using (IRandomAccessStream s = await sf.OpenAsync(FileAccessMode.Read))
                {
                    if (s.Size > 0)
                    {
                        byte[] data = new byte[s.Size];
                        IBuffer i = await s.ReadAsync(
                            data.AsBuffer(0, (int)s.Size), 
                            (uint)s.Size, 
                            InputStreamOptions.Partial);
                        txtMessage.Text=
                            Encoding.UTF8.GetString(i.ToArray(),0,(int)i.Length);
                    }
                }

            }
            catch (Exception ex)
            {

                tbMessage.Text = "Error: " + ex.Message;
            }

        }

        private async void btnDeleteFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFolder sFolder = ApplicationData.Current.LocalFolder;
                sf = await sFolder.GetFileAsync(fileName);
                string name = sf.Name;
                await sf.DeleteAsync();
                sf = null;
                tbMessage.Text = "Delete file " + name + " successful!";

            }
            catch (Exception ex)
            {
                tbMessage.Text = ex.Message;

            }
                    
        }

        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sf != null)
                {
                    using (IRandomAccessStream s = await sf.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        Stream st = s.AsStreamForWrite();
                        st.Seek(st.Length, SeekOrigin.Begin);
                        byte[] data = Encoding.UTF8.GetBytes(txtMessage.Text + Environment.NewLine);
                        st.SetLength(st.Length + data.Length);
                        await st.WriteAsync(data, 0, data.Length);
                        await st.FlushAsync();
                        await s.FlushAsync();
                        tbMessage.Text = "Write file successful!";
                    }
                }
                else
                {
                    tbMessage.Text = "Create file first!";
                }

            }
            catch (Exception ex)
            {
                tbMessage.Text = "Error: " + ex.Message;
            }

        }
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang