Deleting a part
In the last post, I showed you how to use the Packaging API to find a particular part and get that part's URI. The relationship and URI of the particular part are important as you cannot rely on the name of the part being the persisted from save to save.
One action you can take is removing a part from a package. For example, removing the VBA project from a macro-enabled file. I've enclosed a snippet to do this below. Using this snippet you can remove the VBA project from any Office Open XML file. Notice that in both the last post and this one, we have yet to touch any of the XML within the parts. I'll get to that in a future post.
The VBA project is only one of the parts that must require the file to be macro-enabled. XLM sheets are another. In a future snippet, I'll show how to remove all the macro parts and convert the file from macro-enabled to macro-free.
/// <summary>
/// Delete the VBA project part and relationship in any file type.
/// </summary>
/// <param name="fileName">name of the file to delete</param>
public void DeleteVBAPart(string fileName)
{
string officeDocRelType = @"http://schemas.microsoft.com/office/2006/relationships/officeDocument";
const string vbaRelationshipType = "http://schemas.microsoft.com/office/2006/relationships/vbaProject";
PackagePart documentPart = null;
Uri documentUri = null;
//Open the package with Read permission
using (Package officePackage = Package.Open(fileName, FileMode.Open, FileAccess.ReadWrite))
{
//Get the start part
foreach (PackageRelationship relationship in officePackage.GetRelationshipsByType(officeDocRelType))
{
// There should only be one document part in the package
documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
documentPart = officePackage.GetPart(documentUri);
break;
}
//Find the VBA project part.
foreach (System.IO.Packaging.PackageRelationship relationship in documentPart.GetRelationshipsByType(vbaRelationshipType))
{
Uri vbaUri = PackUriHelper.ResolvePartUri(documentUri, relationship.TargetUri);
PackagePart vbaPart = officePackage.GetPart(vbaUri);
//Delete the VBA part
officePackage.DeletePart(vbaUri);
//Remove the VBA relationship
documentPart.DeleteRelationship(relationship.Id);
//There is only VBA part:
break;
}
//Close the package
officePackage.Close();
}
}
Are you all finding these snippets useful? Are there specific scenarios you want to see? Drop me a comment.
Up next: I'll get into the mailbag and answer some reader questions.