I have a document I’ve pulled from a database and put into a MemoryStream object. I have opened up the document and made the necessary changes, and now I want to save the document in the same format with which it was opened.
MemoryStream ms = getDocFromDatabase();
Aspose.Words.Document theDoc = new Aspose.Words.Document(ms);
// various and sundry processing
theDoc.Save(ms, ???);
I’m not sure I will know what the format should be. Is there some way to save in the same format that opened the document? There is Aspose.Words.SaveFormat.Odt, but I don’t think that that is what I’m looking for. There is also Aspose.Words.SaveFormat.None, but I don’t think that that is what I’m looking for. Would I parse the extension of the document and modify the save format accordingly?
Any assistance would be appreciated. Have a nice day!
Sure, you can convert a LoadFormat value to a SaveFormat value (if possible) by using the FileFormatUtil.LoadFormatToSaveFormat method. The following code snippet shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.
// Load the document without a file extension into a stream and
use the DetectFileFormat method to detect it’s format. These are both times
where you might need extract the file format as it’s not visible
FileStream docStream = File.OpenRead(MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);
// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;
// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a string first for working with. The string will include the leading dot in front of the extension.
string fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);
// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);
// Load a document from the stream.
Document doc = new Document(docStream);
// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));