Serializza e lavora con un documento in un database
Una delle attività che potrebbe essere necessario svolgere quando si lavora con i documenti è l’archiviazione e il recupero di oggetti Document da e verso un database. Ad esempio, ciò sarebbe necessario se stessi implementando qualsiasi tipo di sistema di gestione dei contenuti. Tutte le versioni precedenti dei documenti devono essere archiviate nel sistema di database. La possibilità di archiviare documenti nel database è estremamente utile anche quando l’applicazione fornisce un servizio basato sul web.
Aspose.Words offre la possibilità di convertire un documento in un array di byte per il successivo lavoro con questo documento in un database.
Converti un documento in un array di byte
Per archiviare un documento in un database o per preparare un documento per la trasmissione sul web, è spesso necessario serializzare il documento per ottenere un array di byte.
Per serializzare un oggetto Document in Aspose.Words:
- Salvarlo in un MemoryStream utilizzando l’overload del metodo Save della classe Document.
- Chiamare il metodo ToArray, che restituisce un array di byte che rappresenta il documento in formato byte.
I passaggi precedenti possono quindi essere invertiti per caricare nuovamente i byte in un oggetto Document.
L’esempio seguente mostra come serializzare un oggetto Document per ottenere un array di byte e quindi come annullare la serializzazione dell’array di byte per ottenere nuovamente un oggetto 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); |
È possibile scaricare il file modello di questo esempio da Aspose.Words GitHub.
Archiviare, leggere ed eliminare un documento in un database
Questa sezione mostra come salvare un documento in un database e quindi caricarlo nuovamente in un oggetto Document
per lavorarci. Per semplicità, il nome del file è la chiave utilizzata per archiviare e recuperare i documenti dal database. Il database contiene due colonne. La prima colonna “FileName” viene archiviata come stringa e viene utilizzata per identificare i documenti. La seconda colonna “FileContent” viene archiviata come oggetto BLOB
che memorizza l’oggetto documento sotto forma di byte.
Il seguente esempio di codice mostra come impostare una connessione a un database ed eseguire comandi:
// 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(); |
Il seguente esempio di codice mostra come salvare un documento nel database, quindi leggere nuovamente lo stesso documento e infine eliminare il record contenente il documento dal database:
// 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(); |
Salvare un documento in un database
Per salvare un documento in un database convertire questo documento in un array di byte, come descritto all’inizio di questo articolo. Quindi, salva questo array di byte in un campo del database.
Il seguente esempio di codice mostra come salvare un documento nel database specificato:
// 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(); | |
} |
Specifica commandString, che è un’espressione SQL che fa tutto il lavoro:
- Per salvare un documento nel database, viene utilizzato il comando “INSERT INTO” e viene specificata una tabella insieme ai valori di due campi record: FileName e FileContent. Per evitare parametri aggiuntivi, il nome del file viene preso dall’oggetto Document stesso. Al valore del campo
FileContent
vengono assegnati byte dal flusso di memoria, che contiene una rappresentazione binaria del documento archiviato. - La restante riga di codice esegue il comando che memorizza il documento Aspose.Words nel database.
Recuperare un documento da un database
Per recuperare un documento dal database, selezionare il record che contiene i dati del documento come array di byte. Quindi carica l’array di byte dal record in MemoryStream e crea un oggetto Document che caricherà il documento da MemoryStream.
Il seguente esempio di codice mostra come recuperare e restituire un documento dal database specificato utilizzando il nome file come chiave per recuperare questo documento:
// 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; | |
} |
Eliminare un documento da un database
Per eliminare un documento dal database, utilizzare l’apposito comando SQL senza alcuna manipolazione sull’oggetto Document.
L’esempio di codice seguente mostra come eliminare un documento dal database, utilizzando il nome file per recuperare il record:
// 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(); | |
} |