2010-11-24 62 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