UWP打开记事本文件,需要选择编码,win记事本文件默认编码根据系统语言不同而不同,而UWP在C#代码中Encoding下并没有GB2312编码,因此代码读取txt代码略有不同。
首先引用System.Text.Encoding.CodePages(Nuget)
//获取记事本的默认编码(中文为Gb2312)
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); } }
记事本的默认编码是系统内置,但个别用户在保存记事本的时候可能会自定义编码,或者下载了UTF-8格式的记事本,因此考虑了额外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; } } }
DesktopNote(UWP ) 桌面记事本 详情 --> 链接