2017-04-09 36 views
1

我在VS17寫代碼和代碼使用存儲在xlsx文件數據庫(到目前爲止,它被用來通過讀取文件的路徑和使用OLE.DB閱讀它):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(); 

當我想把它編譯成.exe文件我增加了文件轉換成以下列方式的資源:

var fileString = namespace.Properties.Resources.DataBase; 

但是,結果我得到的是fileString是{bytes[28432]}

我怎樣才能使它成爲一個路徑或文件,我實際上可以使用它的單元格中的值作爲數據庫?

謝謝

+0

保存它到一個臨時文件? –

回答

0

隨着線

var fileString = namespace.Properties.Resources.DataBase; 

你得到的字節數組(byte[])和你要使用的字節數組爲路徑,以Excel文件。不幸的是,這是行不通的。當指定fileString作爲文件名時,您得到的那個是byte[],因此{bytes[28432]}

唯一實現你的任務是將該字節寫入(臨時)文件,從中獲取數據,並刪除臨時文件。要做到這一點,你可以做到以下幾點:

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