07 March 2017

Controls: File Pickers với Save File Dialog / Open File Dialog trên Windows Store Apps (C #).

Yêu cầu: Windows 10 và Visual Studio 2015
- File Pickers: Lưu file và Mở File
//Lấy đường dẫn file (path)
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".txt");
file = await picker.PickSingleFileAsync();
tbUrl.Text = file.Path;
//Đọc file tiếp phần đường dẫn path
String text = await FileIO.ReadTextAsync(file);
tbContents.Text = text;
//Lưu file
FileSavePicker saver = new FileSavePicker();
saver.SuggestedStartLocation = PickerLocationId.Desktop;
saver.FileTypeChoices.Add("Text File", new List<string>() { ".txt" });
saver.SuggestedFileName = "text-name";
StorageFile file = await saver.PickSaveFileAsync();

if (file != null)
{
    CachedFileManager.DeferUpdates(file);
    await FileIO.WriteTextAsync(file, this.tbConten.Text);
    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
}
- Example: Select File, Lưu File, Đọc File
MainPage.xaml
Windows Store 2017
<Page
    x:Class="BaiTapFile.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BaiTapFile"
    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}">
        <TextBox x:Name="tbUrl" HorizontalAlignment="Left" Margin="295,140,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="40" Width="425"/>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="164,147,0,0" TextWrapping="Wrap" Text="Path File" VerticalAlignment="Top" FontSize="24"/>
        <TextBox x:Name="tbContents" HorizontalAlignment="Left" Margin="295,235,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="245" Width="425"/>
        <TextBlock x:Name="textBlock1" HorizontalAlignment="Left" Margin="158,235,0,0" TextWrapping="Wrap" Text="Contents" VerticalAlignment="Top" FontSize="24"/>
        <Button x:Name="btnSelect" Content="Select" HorizontalAlignment="Left" Margin="757,137,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.25,-0.789" FontSize="24" Click="btnSelect_Click"/>
        <Button x:Name="btnWrite" Content="Write File" HorizontalAlignment="Left" Margin="292,540,0,0" VerticalAlignment="Top" FontSize="24" Click="btnWrite_Click_1"/>
        <Button x:Name="btnRead" Content="Read File" HorizontalAlignment="Left" Margin="462,540,0,0" VerticalAlignment="Top" FontSize="24" Click="btnRead_Click"/>
        <Button x:Name="btnClear" Content="Clear" HorizontalAlignment="Left" Margin="633,540,0,0" VerticalAlignment="Top" FontSize="24" Click="btnClear_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.Pickers;
using Windows.Storage.Provider;
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.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace BaiTapFile
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
        StorageFile file;

        public object File { get; private set; }

        private async void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            //Lấy path file
            FileOpenPicker picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".txt");
            file = await picker.PickSingleFileAsync();
            tbUrl.Text = file.Path;
        }


        private async void btnRead_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Đọc file
                String text = await FileIO.ReadTextAsync(file);
                tbContents.Text = text;
            }
            catch (Exception)
            {
                tbContents.Text = "Không tìm thấy File!";
            }

        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            //Clear
            this.tbContents.Text = "";
            this.tbUrl.Text = "";
        }

        private async void btnWrite_Click_1(object sender, RoutedEventArgs e)
        {
            //Ghi file
            FileSavePicker saver = new FileSavePicker();
            saver.SuggestedStartLocation = PickerLocationId.Desktop;
            saver.FileTypeChoices.Add("Text File", new List<string>() { ".txt" });
            saver.SuggestedFileName = "text-name";
            StorageFile file = await saver.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteTextAsync(file, this.tbContents.Text);
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
    }
}
- Chạy chương trình:

Đăng bởi: Dương Hữu Đại

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang