/// <summary>
/// Creates a package-level or part-level relationship and its target part
/// (if the target part wasn't already created before). If the sourceTargetFilePath does not exist,
/// then both relationship and part will not be created.
/// </summary>
/// <param name="package"></param>
/// <param name="sourcePart">Set to null for a package-level relationship</param>
/// <param name="sourceTargetFilePath"></param>
/// <param name="targetUri"></param>
/// <param name="targetMimeType"></param>
/// <param name="relationshipTypeUri"></param>
/// <param name="targetPart">The target part that was created</param>
/// <returns>True if relationship and part (if not already created before) was created,
/// False if source file does not exist and thus relationship and part wasn't created.</returns>
private static bool CreateRelationshipAndTargetPart(
System.IO.Packaging.Package package, System.IO.Packaging.PackagePart sourcePart,
string sourceTargetFilePath, string targetUri, string targetMimeType, string relationshipTypeUri,
out System.IO.Packaging.PackagePart targetPart)
{
// TODO add console output for added parts and relationships
targetPart = null;
if (!File.Exists(sourceTargetFilePath))
{
Console.WriteLine(
"Warning: The following source file does not exist: " + sourceTargetFilePath +
". Part and relationship will not be created.");
return(false);
}
try
{
targetPart = package.CreatePart(
PackUriHelper.CreatePartUri(
new Uri(targetUri, UriKind.Relative)), targetMimeType, CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(sourceTargetFilePath, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(targetPart.GetStream());
}
}
catch (InvalidOperationException)
{
Console.WriteLine(
"Warning: The following part URI already exists and will not be created again: " +
targetUri + ". Relationship will still be created.");
}
if (sourcePart == null)
{
package.CreateRelationship(
PackUriHelper.CreatePartUri(
new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
}
else
{
sourcePart.CreateRelationship(
PackUriHelper.CreatePartUri(
new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
}
return(true);
}