Windows Phone从文本文件中读取

时间:2013-12-12 07:48:15

标签: c# windows-phone-7

我正在编写一个从文本文件中读取数据的应用程序,并将其用作应用程序的基础。这只是一个简单的文本文件,包含程序所需的多行数据。我已将文本文件作为Visual Studio中项目的一部分包含在内。但是,当我尝试运行应用程序并使用StreamReader读取文本文件时,它会引发错误:

“System.MethodAccessException:安全透明方法'App.MainPage..ctor()'尝试访问安全关键方法'System.IO.File.Exists(System.String)'失败。    在System.IO.File.Exists(String path)“

此文本文件对应用程序的功能非常重要。当人们下载并直接从应用程序中读取它时,有什么方法可以将它包含在XAP中吗?

2 个答案:

答案 0 :(得分:8)

以下是在wp7 app中从解决方案中读取文本文件的解决方案。

  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();
                  }
    

答案 1 :(得分:0)

您可以使用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");
            }
        }