2017-01-22 83 views
2

我有FileOpenPicker的問題。我使用特殊字符,例如śćE和我的.txt文件的內容有: 「SS CCęó」FileOpenPicker - 如何讀取特殊字符

這是我的代碼:

var picker = new Windows.Storage.Pickers.FileOpenPicker(); 
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; 
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; 
picker.FileTypeFilter.Add(".txt"); 

Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); 
if (file != null) 
{ 
    using (var inputStream = await file.OpenReadAsync()) 
    using (var classicStream = inputStream.AsStreamForRead()) 
    using (var streamReader = new StreamReader(classicStream)) 
    { 
     var something = streamReader.ReadToEnd(); 
    } 
} 

當我閱讀我的文件,我得到這樣的:

enter image description here

我試圖改變文化,編碼並沒有什麼。

這個班的問題如何?

我真的很感激任何幫助或指導。謝謝!

+0

問題可能在您的文件中,首先什麼編碼是您的文本文件?然後使用您未明確指定的相同編碼打開StreamReader。 (我推薦使用UTF8編碼) – kurakura88

回答

0

問題不在於類,而是在於txt文件的編碼。可能你已經將編碼設置爲ANSI,如果你試圖用你的代碼閱讀它,它會給你奇怪的字符。要正確地做到這一點,你將不得不與註冊商一起定義了特定編碼:

var picker = new Windows.Storage.Pickers.FileOpenPicker(); 
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; 
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; 
picker.FileTypeFilter.Add(".txt"); 
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); 
if (file != null) 
{ 
    // register provider - by default encoding is not supported 
    Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); 
    using (var inputStream = await file.OpenReadAsync()) 
    using (var classicStream = inputStream.AsStreamForRead()) 
    using (var streamReader = new StreamReader(classicStream, Encoding.GetEncoding(1250))) 
    { 
     var something = streamReader.ReadToEnd(); 
    } 
} 

容易得多這將是,如果你已經使用UTF-8編碼保存文件,然後你可以有閱讀它只是馬上。

enter image description here