データベース内のドキュメントをシリアル化して操作する

ドキュメントを操作するときに実行する必要があるタスクの 1 つは、Document オブジェクトをデータベースに格納したりデータベースから取得したりすることです。たとえば、何らかのコンテンツ管理システムを実装する場合、これが必要になります。ドキュメントの以前のバージョンはすべてデータベース システムに保存する必要があります。ドキュメントをデータベースに保存する機能は、アプリケーションが Web ベースのサービスを提供する場合にも非常に役立ちます。

Aspose.Words は、データベース内のこのドキュメントをその後処理するために、ドキュメントをバイト配列に変換する機能を提供します。

ドキュメントをバイト配列に変換する

ドキュメントをデータベースに保存したり、Web 経由で送信できるようにドキュメントを準備したりするには、多くの場合、ドキュメントをシリアル化してバイト配列を取得する必要があります。

Document オブジェクトを Aspose.Words でシリアル化するには:

  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 オブジェクトにロードして操作する方法を説明します。わかりやすくするために、ファイル名はデータベースへのドキュメントの保存とデータベースからのドキュメントの取得に使用されるキーです。データベースには 2 つの列が含まれています。最初の列「FileName」は文字列として保存され、ドキュメントを識別するために使用されます。 2列目の「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」コマンドを使用し、テーブルを 2 つのレコード フィールド (FileName と FileContent) の値とともに指定します。追加のパラメータを避けるために、ファイル名は 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;
}

データベースからドキュメントを削除する

データベースからドキュメントを削除するには、Document オブジェクトを操作せずに、適切な SQL コマンドを使用します。

次のコード例は、ファイル名を使用してレコードをフェッチし、データベースからドキュメントを削除する方法を示しています。

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