在phone7中打开一个项目文件

时间:2010-11-24 13:53:28

标签: 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();

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

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

2 个答案:

答案 0 :(得分:8)

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

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

如果您尝试读取/写入此文件,则需要将其复制到隔离存储。 (务必添加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;
 }

在这两种情况下,请确保将文件设置为“资源”,然后将YOURASSEMBLY部件替换为装配件的名称。

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

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

答案 1 :(得分:0)

模拟器无权访问PC文件系统。您必须将文件部署到目标(模拟器)。最简单的方法是将文件标记为嵌入式资源。将文件的Build Action设置为'Resource',然后在运行时使用以下代码提取它:

var res = Application.GetResourceStream(new Uri([nameOfYourFile], UriKind.Relative)) 
相关问题