在phone7中打开一个项目文件

the*_*eXs 4 windows-phone-7

你好,我在VisualStudio中有一个项目,它在根节点下面包含一个'xmlfiles'文件夹.这个文件夹包含一个文件'mensen.xml',我尝试打开它...

但是,当我尝试打开该文件时,调试器会介入并抛出异常.

我试过了 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();
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

Nothin正在工作:(.如何在Phone7模拟器中打开本地文件?

the*_*ent 8

如果您只是打开它来阅读它,那么您可以执行以下操作(假设您已将文件的构建操作设置为资源):

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

如果您尝试读取/写入此文件,则需要将其复制到隔离存储.(一定要加using System.IO.IsolatedStorage)

您可以使用以下方法:

 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;
 }
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,请确保将文件设置为"资源",并使用程序集的名称替换YOURASSEMBLY部分.

使用上述方法,访问您的文件只需执行以下操作:

IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.FileExists(fileName))
{
  CopyFromContentToStorage(fileName);
}
store.OpenFile(fileName, System.IO.FileMode.Append);
Run Code Online (Sandbox Code Playgroud)