开发者

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.Op开发者_高级运维en);            
        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?


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);


The emulator does not have access to the PC file system. You must deploy the file to the target (emulator). The easiest way to do this is mark the file as an embedded Resource. Set the file's Build Action to 'Resource' and then extract it at runtime with code something like this:

var res = Application.GetResourceStream(new Uri([nameOfYourFile], UriKind.Relative)) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜