序列化和使用数据库中的文档

处理文档时可能需要完成的任务之一是在数据库中存储和检索 Document 对象。例如,如果您正在实施任何类型的内容管理系统,则这是必要的。所有以前版本的文档都必须存储在数据库系统中。当您的应用程序提供基于 Web 的服务时,在数据库中存储文档的能力也非常有用。

Aspose.Words 提供了将文档转换为字节数组的功能,以便后续在数据库中使用该文档。

将文档转换为字节数组

为了将文档存储在数据库中或准备文档以便在网络上传输,通常需要序列化文档以获得字节数组。

要在 Aspose.Words 中序列化 Document 对象:

  1. 使用 Document 类的 Save 方法重载将其保存到 MemoryStream
  2. 调用 ToArray 方法,该方法返回以字节形式表示文档的字节数组。

然后可以颠倒上述步骤,将字节加载回 Document 对象。

下面的示例展示了如何序列化 Document 对象以获取字节数组,然后如何反序列化字节数组以再次获取 Document 对象:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
// Create a new memory stream.
MemoryStream outStream = new MemoryStream();
// Save the document to stream.
doc.Save(outStream, SaveFormat.Docx);
// Convert the document to byte form.
byte[] docBytes = outStream.ToArray();
// The bytes are now ready to be stored/transmitted.
// Now reverse the steps to load the bytes back into a document object.
MemoryStream inStream = new MemoryStream(docBytes);
// Load the stream into a new document object.
Document loadDoc = new Document(inStream);

您可以从Aspose.Words GitHub下载本示例的模板文件。

在数据库中存储、读取和删除文档

本节介绍如何将文档保存在数据库中,然后将其加载回 Document 对象中以进行使用。为简单起见,文件名是用于从数据库存储和获取文档的键。该数据库包含两列。第一列"FileName"存储为字符串,用于标识文档。第二列"FileContent"存储为BLOB对象,该对象以字节形式存储文档对象。

以下代码示例展示了如何建立与数据库的连接并执行命令:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string dbName = "";
// Open a database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RunExamples.GetDataDir_Database() + dbName;
OleDbConnection mConnection = new OleDbConnection(connString);
mConnection.Open();

以下代码示例演示如何将文档保存到数据库,然后再次读取同一文档,最后从数据库中删除包含该文档的记录:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Store the document to the database.
StoreToDatabase(doc, mConnection);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(fileName, mConnection);
// Save the retrieved document to disk.
string newFileName = Path.GetFileNameWithoutExtension(fileName) + " from DB" + Path.GetExtension(fileName);
dbDoc.Save(dataDir + newFileName);
// Delete the document from the database.
DeleteFromDatabase(fileName, mConnection);
// Close the connection to the database.
mConnection.Close();

将文档保存到数据库

要将文档保存在数据库中,请将此文档转换为字节数组,如本文开头所述。然后,将此字节数组保存到数据库字段中。

以下代码示例展示了如何将文档保存到指定数据库:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void StoreToDatabase(Document doc, OleDbConnection mConnection)
{
// Save the document to a MemoryStream object.
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Docx);
// Get the filename from the document.
string fileName = Path.GetFileName(doc.OriginalFileName);
// Create the SQL command.
string commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + fileName + "', @Docx)";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Add the @Docx parameter.
command.Parameters.AddWithValue("Docx", stream.ToArray());
// Write the document to the database.
command.ExecuteNonQuery();
}

指定 commandString,它是完成所有工作的 SQL 表达式:

  • 要将文档保存到数据库中,请使用"INSERT INTO"命令并指定一个表以及两个记录字段(文件名和文件内容)的值。为了避免额外的参数,文件名取自 Document 对象本身。 FileContent 字段值是从内存流中分配的字节,其中包含所存储文档的二进制表示形式。
  • 剩余的代码行执行将 Aspose.Words 文档存储在数据库中的命令。

从数据库检索文档

要从数据库检索文档,请选择包含字节数组形式的文档数据的记录。然后将记录中的字节数组加载到 MemoryStream 中,并创建一个将从 MemoryStream 加载文档的 Document 对象。

以下代码示例演示如何使用文件名作为获取该文档的键从指定数据库检索并返回文档:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static Document ReadFromDatabase(string fileName, OleDbConnection mConnection)
{
// Create the SQL command.
string commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Create the data adapter.
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
// Fill the results from the database into a DataTable.
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
// Check there was a matching record found from the database and throw an exception if no record was found.
if (dataTable.Rows.Count == 0)
throw new ArgumentException(string.Format("Could not find any record matching the document \"{0}\" in the database.", fileName));
// The document is stored in byte form in the FileContent column.
// Retrieve these bytes of the first matching record to a new buffer.
byte[] buffer = (byte[])dataTable.Rows[0]["FileContent"];
// Wrap the bytes from the buffer into a new MemoryStream object.
MemoryStream newStream = new MemoryStream(buffer);
// Read the document from the stream.
Document doc = new Document(newStream);
// Return the retrieved document.
return doc;
}

从数据库中删除文档

要从数据库中删除文档,请使用适当的 SQL 命令,而不对 Document 对象进行任何操作。

以下代码示例演示如何使用文件名获取记录来从数据库中删除文档:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void DeleteFromDatabase(string fileName, OleDbConnection mConnection)
{
// Create the SQL command.
string commandString = "DELETE * FROM Documents WHERE FileName='" + fileName + "'";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Delete the record.
command.ExecuteNonQuery();
}