简体   繁体   English

Windows Phone从文本文件中读取

[英]Windows Phone read from text file

I'm writing an app that reads data from a text file and uses that as the basis of the app. 我正在编写一个应用程序,它从文本文件中读取数据并将其用作应用程序的基础。 This is just a simple text file with several lines of data that the program needs. 这只是一个简单的文本文件,包含程序所需的多行数据。 I've included the text file as part of the project in visual studio. 我已将文本文件作为Visual Studio中项目的一部分包含在内。 However, when I try to run the app and read the text file using a StreamReader, it throws an error: 但是,当我尝试运行应用程序并使用StreamReader读取文本文件时,它会抛出一个错误:

"System.MethodAccessException: Attempt by security transparent method 'App.MainPage..ctor()' to access security critical method 'System.IO.File.Exists(System.String)' failed. at System.IO.File.Exists(String path)" “System.MethodAccessException:安全透明方法'App.MainPage..ctor()'尝试访问安全关键方法'System.IO.File.Exists(System.String)'失败。在System.IO.File.Exists(字符串路径)“

This text file is very important to the function of the app. 此文本文件对应用程序的功能非常重要。 Is there any way I can include it with the XAP when people download it and read it directly from within the app? 当人们下载并直接从应用程序中读取它时,有什么方法可以将它包含在XAP中吗?

Here is the solution to read a text file from solution in wp7 app. 这是从wp7应用程序中的解决方案中读取文本文件的解决方案。

  1. Copy text file in your solution. 复制解决方案中的文本文件。

  2. Right Click -> Properties 右键单击 - >属性

  3. Now set Build Action to Resource. 现在将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(); } 

You can use IsolatedStorageFile class to access your text file within your Windows Phone application. 您可以使用IsolatedStorageFile类访问Windows Phone应用程序中的文本文件。 To read it, open a new FileStream . 要阅读它,请打开一个新的FileStream You can then create a StreamReader or a StreamWriter with that FileStream . 然后,您可以使用该FileStream创建StreamReader或StreamWriter。

The following code accesses IsolatedStorageFile and opens a new StreamReader to read the content. 以下代码访问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