Reputation: 579
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. However, when I try to run the app and read the text file using a StreamReader, it throws an error:
"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)"
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?
Upvotes: 2
Views: 7378
Reputation: 2778
Here is the solution to read a text file from solution in wp7 app.
Copy text file in your solution.
Right Click -> Properties
Now set Build Action to 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();
}
Upvotes: 8
Reputation: 937
You can use IsolatedStorageFile
class to access your text file within your Windows Phone application. To read it, open a new FileStream
. You can then create a StreamReader or a StreamWriter with that FileStream
.
The following code accesses IsolatedStorageFile
and opens a new StreamReader to read the content.
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");
}
}
Upvotes: 0