Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a project file in phone7

Howdy, I have a project in VisualStudio which contains a folder 'xmlfiles' below the root node. This folder contains a file 'mensen.xml' which I try to open ...

However when I try to open that very file the debugger steps in and throws an exception.

I tried it with if(File.Exists(@"/xmlfiles/mensen.xml") ) { bool exists = true; } as well as:

        FileStream fs = File.Open("/xmlfiles/mensen.xml", FileMode.Open);            
        TextReader textReader = new StreamReader(fs);
        kantinen = (meineKantinen)deserializer.Deserialize(textReader);
        textReader.Close();

Nothin is working :(. How can I open a local file in the Phone7 Emulator?

like image 780
theXs Avatar asked Feb 25 '23 18:02

theXs


1 Answers

If you are just opening it to read it then you can do the following (Assuming you have set the Build Action of the file to Resource):

System.IO.Stream myFileStream = Application.GetResourceStream(new Uri(@"/YOURASSEMBLY;component/xmlfiles/mensen.xml",UriKind.Relative)).Stream;

If you are attempting to read/write this file then you will need to copy it to Isolated Storage. (Be sure to add using System.IO.IsolatedStorage)

You can use these methods to do so:

 private void CopyFromContentToStorage(String fileName)
 {
   IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
   System.IO.Stream src = Application.GetResourceStream(new Uri(@"/YOURASSEMBLY;component/" + fileName,UriKind.Relative)).Stream;
   IsolatedStorageFileStream dest = new IsolatedStorageFileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, store);
   src.Position = 0;
   CopyStream(src, dest);
   dest.Flush();
   dest.Close();
   src.Close();
   dest.Dispose();
 }

 private static void CopyStream(System.IO.Stream input, IsolatedStorageFileStream output)
 {
   byte[] buffer = new byte[32768];
   long TempPos = input.Position;
   int readCount;
   do
   {
     readCount = input.Read(buffer, 0, buffer.Length);
     if (readCount > 0) { output.Write(buffer, 0, readCount); }
   } while (readCount > 0);
   input.Position = TempPos;
 }

In both cases, be sure the file is set to Resource and you replace the YOURASSEMBLY part with the name of your assembly.

Using the above methods, to access your file just do this:

IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.FileExists(fileName))
{
  CopyFromContentToStorage(fileName);
}
store.OpenFile(fileName, System.IO.FileMode.Append);
like image 99
theChrisKent Avatar answered Mar 08 '23 13:03

theChrisKent