【问题标题】:Windows Phone read from text fileWindows Phone 从文本文件中读取
【发布时间】:2013-12-12 07:48:14
【问题描述】:

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

“System.MethodAccessException:尝试通过安全透明方法 'App.MainPage..ctor()' 访问安全关键方法 'System.IO.File.Exists(System.String)' 失败。 在 System.IO.File.Exists(字符串路径)"

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

【问题讨论】:

标签: c# windows-phone-7


【解决方案1】:

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

【讨论】:

  • 干得好。不错的作品。如果有人想将它分配给 Textblock,那么他/她应该添加这个:texBlock1.Text = text;
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    相关资源
    最近更新 更多