如何将txt,doc等文件以二进制形式保存在数据库中

发布网友 发布时间:2022-04-23 16:11

我来回答

2个回答

热心网友 时间:2022-04-27 15:06

private int WriteToDB(string strName, string strType, ref byte[] Buffer)
{
int nFileID = 0;

// Create connection
OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

// Create Adapter
OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM tblFile", dbConn);

// We need this to get an ID back from the database
dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;

// Create and initialize CommandBuilder
OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);

// Open Connection
dbConn.Open();

// New DataSet
DataSet dbSet = new DataSet();

// Populate DataSet with data
dbAdapt.Fill(dbSet, "tblFile");

// Get reference to our table
DataTable dbTable = dbSet.Tables["tblFile"];

// Create new row
DataRow dbRow = dbTable.NewRow();

// Store data in the row
dbRow["FileName"] = strName;
dbRow["FileSize"] = Buffer.Length;
dbRow["ContentType"] = strType;
dbRow["FileData"] = Buffer;

// Add row back to table
dbTable.Rows.Add(dbRow);

// Update data source
dbAdapt.Update(dbSet, "tblFile");

// Get newFileID
if( !dbRow.IsNull("FileID") )
nFileID = (int)dbRow["FileID"];

// Close connection
dbConn.Close();

// Return FileID
return nFileID;
}
写入库。
private void ShowTheFile(int FileID)
{
// Define SQL select statement
string SQL = "SELECT FileSize, FileData, ContentType FROM tblFile WHERE FileID = "
+ FileID.ToString();

// Create Connection object
OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

// Create Command Object
OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

// Open Connection
dbConn.Open();

// Execute command and receive DataReader
OleDbDataReader dbRead = dbComm.ExecuteReader();

// Read row
dbRead.Read();

// Clear Response buffer
Response.Clear();

// Set ContentType to the ContentType of our file
Response.ContentType = (string)dbRead["ContentType"];

// Write data out of database into Output Stream
Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);

// Close database connection
dbConn.Close();

// End the page
Response.End();
}
读出

热心网友 时间:2022-04-27 16:24

格式改成**.reg
另存!

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com