UWP读取TXT记事本文件代码

关键词:
UWP打开记事本文件,需要选择编码,win记事本文件默认编码为ANSI,而UWP在C#代码中Encoding下并没有ANSI编码,因此代码略有不同。

//获取记事本的ANSI编码

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var encoding = Encoding.GetEncoding(0);

下面是根据以上编码通过流读取txt文本的方法;\

using (Stream stream = await file.OpenStreamForReadAsync())
{
    using (StreamReader reader = new StreamReader(stream,encoding,false))
    {
        string s = reader.ReadToEnd();
        redit.Document.SetText(TextSetOptions.None, s);
    }
}

记事本的默认编码是ANSI,但个别用户在保存记事本的时候可能会自定义编码,因此考虑了额外UTF8编码,下面是通过Stream读取txt笔记本的代码,

下面是全部代码:

private async void OpenLocalRtf(StorageFile file)
   {
       if (file != null)//传入了文件或者存在默认文件
       {
           string tail = file.Name.Substring(file.Name.Length - 3, 3);
           switch (tail)
           {
               case "txt":
                   //获取记事本的编码
                   Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                   var encoding = Encoding.GetEncoding(0);
                   var dialog = new MessageDialog("txt文件的编码是?" );
                   dialog.Commands.Add(new UICommand("ANSI(默认)", cmd =>
                   {
                       encoding = Encoding.GetEncoding(0);
                   }, commandId: 0));
                   dialog.Commands.Add(new UICommand("UTF-8", cmd => 
                   {
                       encoding = Encoding.UTF8;
                   }, commandId: 1));
                   //设置默认按钮,不设置的话默认的确认按钮是第一个按钮
                   dialog.DefaultCommandIndex = 0;
                   dialog.CancelCommandIndex = 1;
                   //获取返回值
                   await dialog.ShowAsync();
                   using (Stream stream = await file.OpenStreamForReadAsync())
                   {
                       using (StreamReader reader = new StreamReader(stream,encoding,false))
                       {
                           string s = reader.ReadToEnd();
                           redit.Document.SetText(TextSetOptions.None, s);
                       }
                   }
                   break;
               case "rtf":
                   CurrentFileName = file.Name;
                   ClientSetting.DefaultFileName = CurrentFileName;
                   using (IRandomAccessStream randAccStream = await file.OpenAsync(FileAccessMode.Read))
                   {
                       redit.Document.LoadFromStream(TextSetOptions.FormatRtf, randAccStream);
                   }
                   break;
               default:
                   break;
           }
       }
   }

作者:songshizhao 发表于:2017-12-01T12:52:05 访问量:1270