views:

104

answers:

3

i m developing an app in windows phone 7 in which i need to read a text file. i write a code for that but when i debug that code, it gives an error "method access exception". same code is working in c# windows form app. i dont know what is the problem. plz suggest me for this and solve this problem. my code is like this:

namespace fileread
{
    public partial class MainPage : PhoneApplicationPage
    {

        private string line;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            StreamReader sr = new StreamReader(@"D:\abc.txt");
            line = sr.ReadLine();
            MessageBox.Show(line);
        }

Error occured at line: "line = sr.ReadLine();"

+3  A: 

Just as most other modern mobile devices, applications running on WP7 are sandboxed for security and reliability reasons. This also means you can't do random I/O on the the way you'd do it in an unrestricted environment.

WP7 does provide sandboxed persistence using familiar constructs as directories and files, within what is known as Isolated Storage. Try to look up IsolatedStorageFile.GetUserStoreForApplication() and take it from there.

Update: An example can be found here.

Cumbayah
k...but can u plz describe me in more detail, what i'll do next. i m newer to development. some detail in code form....
A: 

I Dont think Mobile have D/C Drives;

check out this link; http://social.msdn.microsoft.com/Forums/en/mktplace/thread/129408d0-57f4-406e-8162-c229207d499a

KhanZeeshan
A: 

Are you trying to open a file on your actual computer in this line, from the WP7 emulator?

StreamReader sr = new StreamReader(@"D:\abc.txt");

You definitely won't be able to do this from the phone since applications are isolated from each other for security reasons.

If you need to read in a static text file, consider include it as part of your project and referencing it there instead, using the System.Windows.Application.GetResourceStream method:

var resource = System.Windows.Application.GetResourceStream(new Uri("textfile.txt", UriKind.Relative)

See this question for more info.

Blakomen
k. what to do next...means how to read file and show that data with messagebox.show method. can u explain more?? in code form like first point
So if you just put your txt file in your solution, set the build action to resource, and use the GetResourceStream method, you can read the contents of the txt file as a string with something like TextReader and pass that to a Textbox, or something similar. There is *no* MessageBox.Show() method for WP7.
Blakomen