2010-11-24 57 views
4

Howdy, 我在VisualStudio中有一个项目,其中包含根节点下的文件夹'xmlfiles'。此文件夹包含文件'mensen.xml',我试图打开它...在phone7中打开项目文件

但是,当我尝试打开该文件时,调试器步入并引发异常。

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

没什么工作:(尝试过。 我怎样才能在Phone7的仿真器打开本地文件?

+0

嗨theXs,如果你的目的是要能修改此文件,然后将其复制到每ChrisKent的建议独立存储还是不错的。如果您只想读取文件,则不会像Ctacke和Matt所建议的那样,从xap文件中读取它作为内容或资源(取决于您是否想要分别导致负载惯性 - 延迟负载和启动)。 – 2010-11-24 22:37:27

回答

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

仿真器不能访问到PC的文件系统。您必须将文件部署到目标(模拟器),最简单的方法是将文件标记为嵌入式资源,将文件的构建操作设置为“资源”,然后在运行时使用如下代码将其解压缩:

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

如果以这种方式显式访问/加载文件(并且仅此),请将构建操作设置为“内容”。这样做可以防止在应用程序启动时加载资源,从而帮助启动时间性能。 – 2010-11-24 14:09:54