2010-04-03 46 views
3

我有一個我想嵌入到C#程序集中的excel文件。我已將XLSX文件的構建操作更改爲「嵌入式資源」。如何從.NET程序集中檢索二進制文件?

在運行時,我必須從程序集中檢索這個XLSX文件。

Assembly assembly = Assembly.GetExecutingAssembly(); 
StreamReader sr = new StreamReader(assembly.GetManifestResourceStream("AssemblyName.Output.xlsx"), true); 
StreamWriter sw = new StreamWriter(strPath); 
sw.Write(sr.ReadToEnd()); 
sr.Dispose(); 
sw.Dispose(); 
System.Diagnostics.Process.Start(strPath); 

正如預期的那樣,XLSX文件因爲是二進制數據而失敗。這可以適用於一個文本文件。

我試過二進制讀/寫,但我無法讓代碼運行。思考?

回答

10
var assembly = Assembly.GetExecutingAssembly(); 

// don't forget to do appropriate exception handling arund opening and writing file 
using(Stream input = assembly.GetManifestResourceStream("AssemblyName.Output.xlsx")) 
using(Stream output = File.Open("output.xlsx")) 
{ 
    input.CopyTo(output); 
} 
相關問題