But problem is ContentType is readonly
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri("word//document.xml", UriKind.Relative));
PackagePart DocPart = DocumentPackage.GetPart(partUriDocument);
DocPart.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
DocPart.ContentType is readonly.
For template its value is application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml
For documents it should be application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml
I had tried removing a Part and adding a new Part but this was causing some other error during opening the document from word and also the package was increasing in file size.
Hi,
This sample code will convert dotx file to docx file.
const string documentRelationshipType =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; const string wordDOCXContentType =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"; string docName = @"c:\test9\1nameis.dotx"; Package wdPackage = Package.Open(docName, FileMode.Open, FileAccess.ReadWrite); PackagePart documentPart = null; Uri documentUri = null;
// Get the main document part (document.xml). foreach (System.IO.Packaging.PackageRelationship relationship in
wdPackage.GetRelationshipsByType(documentRelationshipType)) { documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
relationship.TargetUri); documentPart = wdPackage.GetPart(documentUri); // There is only one document. break; }
XmlDocument xdoc = new XmlDocument(); xdoc.Load(documentPart.GetStream());
// Delete the document part and its relationship part. wdPackage.DeletePart(documentPart.Uri);
// Create new document and relationship parts using the correct content types. documentPart = wdPackage.CreatePart(documentUri, wordDOCXContentType); xdoc.Save(documentPart.GetStream(FileMode.Create, FileAccess.Write)); wdPackage.Close();
string newFileName = Path.GetDirectoryName(docName) + @"\" +
Path.GetFileNameWithoutExtension(docName) + ".docx"; // If the new file exists, delete it. You might // want to make this code less destructive. if (File.Exists(newFileName)) { File.Delete(newFileName); } File.Move(docName, newFileName);
Sheela