2013-05-22 94 views
0

我在WP8中讀取文件時遇到問題。在WP8中讀取文件

string text; 
IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; 

IStorageFile storageFile = await applicationFolder.GetFileAsync("MyFile.txt"); 
IRandomAccessStream accessStream = await storageFile.OpenReadAsync(); 

using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size)) 
{ 
    byte[] content = new byte[stream.Length]; 
    await stream.ReadAsync(content, 0, (int)stream.Length); 

    text = Encoding.UTF8.GetString(content, 0, content.Length); 
} 

return text; 

有時storagefileaccessStream崩潰沒有理由。 如果我調試它們,它的工作原理。

我不知道爲什麼。誰能幫我?

回答

0

我正在使用這段代碼。結果將是你的txt文件中的文本,縮寫爲一個字符串,所以假設你的txt文件包含這個。

This 
is 
a test. 

結果將是

This\nis\na\test. 

然後,所有你需要做的就是把它們分開。 string result = null;

IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); 
if (store.FileExists("services.txt")) 
{ 
    using (var stream = new IsolatedStorageFileStream("services.txt", FileMode.Open, store)) 
    { 
     using (var fileReader = new StreamReader(stream)) 
     { 
      result = fileReader.ReadToEnd(); 
     } 
    } 
} 

這是我如何拆分消息。

string[] tmp = result.Split(new char[] { '\r', '\n', '.' }); 
foreach (string str in tmp) 
{ 
    System.Diagnostics.Debug.WriteLine(str); 
} 

希望這會有所幫助。

+0

謝謝你,它的工作原理:D –

+0

非常歡迎! – Jieqin