簡體   English   中英

Windows Phone從文本文件中讀取

[英]Windows Phone read from text file

我正在編寫一個應用程序,它從文本文件中讀取數據並將其用作應用程序的基礎。 這只是一個簡單的文本文件,包含程序所需的多行數據。 我已將文本文件作為Visual Studio中項目的一部分包含在內。 但是,當我嘗試運行應用程序並使用StreamReader讀取文本文件時,它會拋出一個錯誤:

“System.MethodAccessException:安全透明方法'App.MainPage..ctor()'嘗試訪問安全關鍵方法'System.IO.File.Exists(System.String)'失敗。在System.IO.File.Exists(字符串路徑)“

此文本文件對應用程序的功能非常重要。 當人們下載並直接從應用程序中讀取它時,有什么方法可以將它包含在XAP中嗎?

這是從wp7應用程序中的解決方案中讀取文本文件的解決方案。

  1. 復制解決方案中的文本文件。

  2. 右鍵單擊 - >屬性

  3. 現在將Build Action設置為Resource。

     System.IO.Stream src = Application.GetResourceStream(new Uri("solutionname;component/text file name", UriKind.Relative)).Stream; using (StreamReader sr = new StreamReader(src)) { string text = sr.ReadToEnd(); } 

您可以使用IsolatedStorageFile類訪問Windows Phone應用程序中的文本文件。 要閱讀它,請打開一個新的FileStream 然后,您可以使用該FileStream創建StreamReader或StreamWriter。

以下代碼訪問IsolatedStorageFile並打開一個新的StreamReader來讀取內容。

        using (IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForApplication())
        {
            //To read
            using (StreamReader r = new StreamReader(f.OpenFile("settings.txt", FileMode.OpenOrCreate)))
            {
                string text = r.ReadToEnd();
            }

            //To write
            using (StreamWriter w = new StreamWriter(f.OpenFile("settings.txt", FileMode.Create)))
            {
                w.Write("Hello World");
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM