2017-04-09 3 views
1

schrieb ich Code in VS17 und dass Code verwendet eine Datenbank in xlsx Datei gespeichert (obwohl es bisher durch das Lesen der Pfad der Datei und liest sie mit OLE.DB verwendet wurde):embeding XLSX fileinto exe C#

string DataBase_File = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), String.Format("{0}", db_name)); 

string constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=NO""", DataBase_File); 
using (OleDbConnection conn = new OleDbConnection(constr)) 
{ 
    conn.Open(); 
    OleDbCommand command = new OleDbCommand(string.Format("Select * from [{0}]", SheetName), conn); 
    OleDbDataReader reader = command.ExecuteReader(); 
i hinzugefügt, um die Datei in die Ressourcen in der folgenden Art und Weise

Wenn ich es in .exe Datei kompilieren will:

var fileString = namespace.Properties.Resources.DataBase; 

jedoch das Ergebnis i bekommen ist, dass fileString {bytes[28432]} ist.

Wie kann ich einen Pfad oder eine Datei erstellen, die ich tatsächlich die Werte in den Zellen als Datenbank verwenden kann?

danke

+0

Speichern Sie es in eine temporäre Datei? –

Antwort

0

Mit Linie

var fileString = namespace.Properties.Resources.DataBase; 

Sie bekommen Byte-Array (byte[]) und Sie versuchen, dieses Byte-Array als Pfad-Datei auf Ihrer Excel zu verwenden. Leider kann das nicht funktionieren. Wenn Sie fileString als Dateinamen angeben, erhalten Sie .ToString() von diesem byte[], daher {bytes[28432]}.

Die einzige Aufgabe war es, diese Bytes in (temporäre) Datei zu schreiben, Daten daraus zu bekommen und temporäre Dateien zu löschen. Um dies zu erreichen, können Sie Folgendes tun:

//temp file path 
string tempDbPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString(); 
//temp db file name 
string tempDbFile = "tempdb.xlsx"; 
//path + filename 
string tempDBLocation = Path.Combine(tempDbPath, tempDbFile); 
//get byte array from application's resources 
byte[] resourceBytes = Properties.Resources.DataBase; 

//write all bytes to specified location 
File.WriteAllBytes(tempDBLocation, resourceBytes); 

//connect and select data as usual 
string constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=NO""", tempDBLocation); 
using (OleDbConnection conn = new OleDbConnection(constr)) 
{ 
    conn.Open(); 
    OleDbCommand command = new OleDbCommand(string.Format("Select * from [{0}]", "Sheet1$"), conn); 
    OleDbDataReader reader = command.ExecuteReader(); 
} 

//delete temp file 
File.Delete(tempDBLocation);