2010-04-03 8 views
3

J'ai un fichier Excel que je veux intégrer dans mon assembly C#. J'ai changé l'action de construction du fichier XLSX à "Embedded Resource".Comment récupérer un fichier binaire à partir de l'assembly .NET?

Pendant l'exécution, je dois récupérer ce fichier XLSX à partir de l'assembly.

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

Comme prévu, cela ne fonctionne pas pour le fichier XLSX car il est une donnée binaire. Cela pourrait bien fonctionner avec un fichier texte.

J'ai essayé la lecture/écriture binaire, mais je n'arrive pas à faire fonctionner le code. Pensées?

Répondre

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); 
} 
Questions connexes