Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file from Windows Phone 7

I have a folder called data/ in my project that contains txt files.

I configured Build Action to resources to all files.

I tried these different ways:

method 1

var resource = Application.GetResourceStream(new Uri(fName, UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
Debug.WriteLine(streamReader.ReadToEnd());

method 2

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileNames = myIsolatedStorage.GetFileNames("*.txt");

method 3

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
   using (StreamReader fileReader = new StreamReader(new IsolatedStorageFileStream(fName, FileMode.Open, isf)))
   {
      while (!fileReader.EndOfStream)
      {
        string line = fileReader.ReadLine();
        al.Add(line);
        Debug.WriteLine(line);
      }
   }
}

Now, i tried different ways to read files without success, why?
Where is the problem?

What's wrong with these methods?

fName is the name of the file.
It's necessary the full path data/filename.txt? It's indifferent...

please help me with this stupid issue,
thanks.

like image 890
elp Avatar asked Jan 16 '23 17:01

elp


1 Answers

Your 2nd & 3rd approaches are wrong. When you include a text file locally in your app, you can't refer it via the IS. Instead, use this function, it will return the file content if found else it will return "null". It works for me, hope it works for you.

Note, if the file is set as content, the filePath = "data/filename.txt" but if it is set as resource it should be referred like this filePath = "/ProjectName;component/data/filename.txt". That may be why your 1st approach might have failed.

    private string ReadFile(string filePath)
    {
        //this verse is loaded for the first time so fill it from the text file
        var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
        if (ResrouceStream != null)
        {
            Stream myFileStream = ResrouceStream.Stream;
            if (myFileStream.CanRead)
            {
                StreamReader myStreamReader = new StreamReader(myFileStream);

                //read the content here
                return myStreamReader.ReadToEnd();
            }
        }
        return "NULL";
    }
like image 65
Milan Aggarwal Avatar answered Jan 28 '23 10:01

Milan Aggarwal