2011-06-30 62 views
2

當我第一次在Windows Phone上啓動我的應用程序時,我想從項目文件夾中獲取一些文件(xml/images)並將它們寫入隔離存儲。如何從項目文件夾讀取文件?

如何檢測到我的應用程序是第一次運行?

如何訪問項目文件夾中的文件?

回答

1

如果您的項目文件夾與Visual Studio項目中的文件夾一樣,我通常會右鍵單擊這些文件並將構建操作設置爲「嵌入式資源」。在運行時,你可以像這樣從嵌入式資源讀取數據:

// The resource name will correspond to the namespace and path in the file system. 
// Have a look at the resources collection in the debugger to figure out the name. 
string resourcePath = "assembly namespace" + "path inside project"; 
Assembly assembly = Assembly.GetExecutingAssembly(); 
string[] resources = assembly .GetManifestResourceNames(); 
List<string> files = new List<string>(); 

if (resource.StartsWith(resourcePath)) 
{ 
    StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resource), Encoding.Default); 
    files.Add(reader.ReadToEnd()); 
} 

要讀取的圖像,你需要像這樣來讀取數據流:

public static byte[] ReadAllBytes(Stream input) 
    { 
     byte[] buffer = new byte[32 * 1024]; 

     using (MemoryStream ms = new MemoryStream()) 
     { 
      int read; 

      while ((read = input.Read(buffer, 0, buffer.Length)) > 0) 
      { 
       ms.Write(buffer, 0, read); 
      } 

      return ms.ToArray(); 
     } 
    } 
+0

謝謝亞歷克斯,非常好的解釋, – Ishti

+0

是否有可能更新/刪除/添加文件到項目文件夾? – Ishti

+0

@Ishti不,不可能添加,編輯或刪除分佈在XAP中或嵌入程序集中的文件(如本例中)。不過,您可以使用IsolatedStorage中的文件執行這些操作。 (請參閱http://msdn.microsoft.com/en-us/library/ff402541(v=vs.92).aspx)除非您有一個非常好的理由,否則最好使用'Resources'而不是正如Vivek所建議的那樣,嵌入式資源。 –

9

這裏是另一種方式來閱讀來自您的visual studio項目的文件。下面顯示如何讀取txt文件,但也可以用於其他文件。這裏的文件和.xaml.cs文件在同一個目錄下。

var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative)); 
var txt = new StreamReader(res.Stream).ReadToEnd(); 

確保您的文件被標記爲內容。

相關問題