本文整理汇总了C#中System.IO.Packaging.Package类的典型用法代码示例。如果您正苦于以下问题:C# Package类的具体用法?C# Package怎么用?C# Package使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Package类属于System.IO.Packaging命名空间,在下文中一共展示了Package类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateDocSettings
public static bool CreateDocSettings(Package pkg, string sDataSource)
{
PackagePart prt;
Stream stm = StmCreatePart(pkg, "/word/settings.xml", s_sUriContentTypeSettings, out prt);
XmlTextWriter xw = new XmlTextWriter(stm, System.Text.Encoding.UTF8);
StartElement(xw, "settings");
WriteElementFull(xw, "view", new[] {"web"});
StartElement(xw, "mailMerge");
WriteElementFull(xw, "mainDocumentType", new[] {"email"});
WriteElementFull(xw, "linkToQuery", (string[])null);
WriteElementFull(xw, "dataType", new[] {"textFile"});
WriteElementFull(xw, "connectString", new[] {""});
WriteElementFull(xw, "query", new[] {String.Format("SELECT * FROM {0}", sDataSource)});
PackageRelationship rel = prt.CreateRelationship( new System.Uri(String.Format("file:///{0}", sDataSource), UriKind.Absolute), TargetMode.External, s_sUriMailMergeRelType);
StartElement(xw, "dataSource");
xw.WriteAttributeString("id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", rel.Id);
EndElement(xw);
StartElement(xw, "odso");
StartElement(xw, "fieldMapData");
WriteElementFull(xw, "type", new[] {"dbColumn"});
WriteElementFull(xw, "name", new[] {"email"});
WriteElementFull(xw, "mappedName", new[] {"E-mail Address"});
WriteElementFull(xw, "column", new[] {"0"});
WriteElementFull(xw, "lid", new[] {"en-US"});
EndElement(xw); // fieldMapData
EndElement(xw); // odso
EndElement(xw); // mailMerge
EndElement(xw); // settings
xw.Flush();
stm.Flush();
return true;
}
示例2: CreateCodeBaseXML
public void CreateCodeBaseXML()
{
try
{
package = Package.Open(fileCodeBase);
XmlDocument sharedString = GetPartFile(OfficeFilePart.ShareString, 0);
sharedString.Save(Common.SHARED_STRING);
XmlDocument sheet = GetPartFile(OfficeFilePart.Sheet, 1);
XsltArgumentList xsltArgListSheet = new XsltArgumentList();
XsltSettings settings = new XsltSettings(true, true);
XslCompiledTransform xslTransSheet = new XslCompiledTransform();
xslTransSheet.Load(Common.XSLT_CODE_BASE, settings, new XmlUrlResolver());
xsltArgListSheet.AddParam("prmDocSharedStrings", "", sharedString.CreateNavigator());
string sOutXmlSheet = System.String.Empty;
using (FileStream fs = new FileStream(Common.XML_CODE_BASE, FileMode.Create))
{
xslTransSheet.Transform(sheet.CreateNavigator(), xsltArgListSheet, fs);
}
XslCompiledTransform xslRowSheet = new XslCompiledTransform();
xslRowSheet.Load(Common.XSLT_TO_ROW);
xslRowSheet.Transform(Common.XML_CODE_BASE, Common.XML_ROW);
}
finally
{
package.Close();
}
}
示例3: Open
public bool Open(string path)
{
try
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
memStream = new MemoryStream();
memStream.Write(buffer, 0, (int)fs.Length);
buffer = null;
fs.Close();
package = Package.Open(memStream, FileMode.Open, FileAccess.ReadWrite);
docParts = new Dictionary<string, DocumentPart>();
PackagePartCollection parts = package.GetParts();
foreach (PackagePart part in parts)
{
DocumentPart docPart = new DocumentPart(part);
docParts.Add(part.Uri.ToString(), docPart);
}
filePath = path;
dirty = false;
return true;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
return false;
}
}
开发者ID:VitorX,项目名称:Open-XML-Package-Editor-Power-Tool-for-Visual-Studio,代码行数:33,代码来源:DocumentPackage.cs
示例4: UpdatePackageManifest
private void UpdatePackageManifest(Package package, PackagePart updatedPart)
{
if (package == null)
throw new ArgumentNullException(nameof(package));
if (updatedPart == null)
throw new ArgumentNullException(nameof(updatedPart));
if (package.FileOpenAccess != FileAccess.ReadWrite)
throw new InvalidOperationException("Package must be open for reading and writing");
var manifestRelation = package.GetRelationship("MANIFEST");
var manifestPart = package.GetPart(manifestRelation.TargetUri);
// parse manifest
var manifest = new PackageManifest(manifestPart, null);
// rehash updated part
var csDefPart = manifest.Items.FirstOrDefault(i => i.PartUri == updatedPart.Uri);
if (csDefPart == null)
throw new InvalidOperationException(string.Format("Unable to find part '{0}' in package manifest", updatedPart.Uri));
csDefPart.Hash = manifest.HashAlgorithm.ComputeHash(updatedPart.GetStream(FileMode.Open, FileAccess.Read)); ;
csDefPart.ModifiedDate = DateTime.UtcNow;
var manifestStream = manifestPart.GetStream(FileMode.Open, FileAccess.Write);
manifest.WriteToStream(manifestStream);
}
示例5: CopyPackage
private static void CopyPackage(Package inputPackage, Package outputPackage)
{
foreach (var inputPart in inputPackage.GetParts())
{
CreateNewPart(inputPart, outputPackage);
}
}
示例6: ShowPrintPreview
private void ShowPrintPreview()
{
// We have to clone the FlowDocument before we use different pagination settings for the export.
RichTextDocument document = (RichTextDocument)fileService.ActiveDocument;
FlowDocument clone = document.CloneContent();
clone.ColumnWidth = double.PositiveInfinity;
// Create a package for the XPS document
MemoryStream packageStream = new MemoryStream();
package = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite);
// Create a XPS document with the path "pack://temp.xps"
PackageStore.AddPackage(new Uri(PackagePath), package);
xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, PackagePath);
// Serialize the XPS document
XpsSerializationManager serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
DocumentPaginator paginator = ((IDocumentPaginatorSource)clone).DocumentPaginator;
serializer.SaveAsXaml(paginator);
// Get the fixed document sequence
FixedDocumentSequence documentSequence = xpsDocument.GetFixedDocumentSequence();
// Create and show the print preview view
PrintPreviewViewModel printPreviewViewModel = printPreviewViewModelFactory.CreateExport().Value;
printPreviewViewModel.Document = documentSequence;
previousView = shellViewModel.ContentView;
shellViewModel.ContentView = printPreviewViewModel.View;
shellViewModel.IsPrintPreviewVisible = true;
printPreviewCommand.RaiseCanExecuteChanged();
}
示例7: Generate
public void Generate(Package sourcePackage, Package targetPackage, FileInfo outputFile)
{
var serializer = new XmlSerializer(typeof(DataSchemaModel));
var uri = PackUriHelper.CreatePartUri(new Uri("/replication.xml", UriKind.Relative));
var sourceModel = (DataSchemaModel)serializer.Deserialize(sourcePackage.GetPart(uri).GetStream());
var targetModel = (DataSchemaModel)serializer.Deserialize(targetPackage.GetPart(uri).GetStream());
var outputFileSql = new List<string>();
foreach (var publicationToCreate in sourceModel.Model.Elements.Except(targetModel.Model.Elements, x => x.Name))
{
var createPublicationStep = new CreatePublicationStep(publicationToCreate);
outputFileSql.AddRange(createPublicationStep.GenerateTSQL());
}
foreach (var publicationToAlter in sourceModel.Model.Elements.Intersect(targetModel.Model.Elements, x => x.Name))
{
var sqlPublicationComparer = new SqlPublicationComparer();
var matchingPublicationInTarget = targetModel.Model.Elements.Single(x => x.Name == publicationToAlter.Name);
var alterPublicationStep = new AlterPublicationStep(sqlPublicationComparer.Compare(publicationToAlter, matchingPublicationInTarget));
outputFileSql.AddRange(alterPublicationStep.GenerateTSQL());
}
foreach (var publicationToDrop in targetModel.Model.Elements.Except(sourceModel.Model.Elements, x => x.Name))
{
var dropPublicationStep = new DropPublicationStep(publicationToDrop);
outputFileSql.AddRange(dropPublicationStep.GenerateTSQL());
}
}
示例8: AddContent
void AddContent(Package package, PackageDefinition manifest, Uri partUri, string file)
{
var part =
package.CreatePart(
PackUriHelper.CreatePartUri(partUri), System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum);
using (var partStream = part.GetStream())
using (var fileStream = fileSystem.OpenFile(file, FileMode.Open))
{
fileStream.CopyTo(partStream);
partStream.Flush();
fileStream.Position = 0;
var hashAlgorithm = new SHA256Managed();
hashAlgorithm.ComputeHash(fileStream);
manifest.Contents.Add(new ContentDefinition
{
Name = partUri.ToString(),
Description =
new ContentDescription
{
DataStorePath = partUri,
LengthInBytes = (int) fileStream.Length,
HashAlgorithm = IntegrityCheckHashAlgorithm.Sha256,
Hash = Convert.ToBase64String(hashAlgorithm.Hash)
}
});
}
}
示例9: CleanWorksheetRelsDocument
private static void CleanWorksheetRelsDocument(Package excelPackage, string sheetName)
{
string worksheetRelsFilePath = @"xl\worksheets\_rels\" + sheetName + ".rels";
PackagePart worksheetRelsPart = GetPackagePart(excelPackage, worksheetRelsFilePath);
if (worksheetRelsPart != null)
{
XmlDocument worksheetRelsDocument = GetXmlDocumentFromPackagePart(worksheetRelsPart);
List<XmlNode> nodesToRemove = new List<XmlNode>();
foreach (XmlNode worksheetRelsNode in worksheetRelsDocument.DocumentElement.ChildNodes)
{
if (worksheetRelsNode.Attributes["TargetMode"] != null)
{
// remove relationships to external files
if (worksheetRelsNode.Attributes["TargetMode"].Value == "External")
{
nodesToRemove.Add(worksheetRelsNode);
}
}
}
if (nodesToRemove.Count > 0)
{
RemoveNodes(nodesToRemove);
SaveXmlDocumentToPackagePart(worksheetRelsPart, worksheetRelsDocument);
}
}
}
示例10: ExcelPackage
/// <summary>
/// Creates a new instance of the ExcelPackage class based on a existing file or creates a new file.
/// </summary>
/// <param name="newFile">If newFile exists, it is opened. Otherwise it is created from scratch.</param>
private ExcelPackage(FileInfo newFile)
{
_outputFolderPath = newFile.DirectoryName;
if (newFile.Exists)
{
// open the existing package
_package = Package.Open(newFile.FullName, FileMode.Open, FileAccess.ReadWrite);
}
else
{
// create a new package and add the main workbook.xml part
_package = Package.Open(newFile.FullName, FileMode.Create, FileAccess.ReadWrite);
// save a temporary part to create the default application/xml content type
var uriDefaultContentType = new Uri("/default.xml", UriKind.Relative);
var partTemp = _package.CreatePart(uriDefaultContentType, "application/xml");
var workbook = Workbook.WorkbookXml; // this will create the workbook xml in the package
// create the relationship to the main part
_package.CreateRelationship(Workbook.WorkbookUri,
TargetMode.Internal,
schemaRelationships + "/officeDocument");
// remove the temporary part that created the default xml content type
_package.DeletePart(uriDefaultContentType);
}
}
示例11: ExportMatrixPart
private static void ExportMatrixPart(Package package, WfProcessDescriptor processDesp, WfExportProcessDescriptorContext context)
{
var matrix = WfMatrixAdapter.Instance.LoadByProcessKey(processDesp.Key, false);
if (matrix == null)
return;
matrix.Loaded = true;
Uri partUri = CreatePartUri(context.MatrixCounter.ToString(), WfProcessDescriptorPackagePartType.MatrixPart);
if (context.ExistingParts.Contains(partUri.ToString()))
return;
context.MappingInfo.Add(new WfPackageRelationMapping()
{
MatrixPath = partUri.ToString(),
MatrixDefID = matrix.Definition.Key,
ProcessDescriptionID = processDesp.Key
});
ExportMatrixDefPart(package, matrix.Definition, context);
PackagePart part = package.CreatePart(partUri, MediaTypeNames.Application.Octet, CompressionOption.Normal);
using (MemoryStream bytes = matrix.ExportToExcel2007(context.ExportParams.MatrixRoleAsPerson))
{
using (Stream stream = part.GetStream())
{
bytes.CopyTo(stream);
}
}
context.ExistingParts.Add(partUri.ToString());
context.MatrixCounter++;
}
示例12: ZipDirectory
private void ZipDirectory(string SourceFolderPath, Package package,int deviceType)
{
DirectoryInfo dir = new DirectoryInfo(SourceFolderPath);
FileInfo[] files=dir.GetFiles();
foreach (FileInfo fi in files)
{
if ((".tdb".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 1) || (".dat".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 2)
|| (".doc".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 2) || ".crd".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) || deviceType == 3)
{
string relativePath = fi.FullName.Replace(SourceFolderPath, string.Empty);
relativePath = relativePath.Replace("\\", "/");
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(relativePath, UriKind.Relative));
//resourcePath="Resource\Image.jpg"
//Uri partUriResource = PackUriHelper.CreatePartUri(new Uri(resourcePath, UriKind.Relative));
PackagePart part = package.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Application.Zip);
using (FileStream fs = fi.OpenRead())
{
using (Stream partStream = part.GetStream())
{
CopyStream(fs, partStream);
fs.Close();
partStream.Close();
}
}
}
}
DirectoryInfo[] directories = dir.GetDirectories();
foreach (DirectoryInfo subDi in directories)
{
ZipDirectory(SourceFolderPath, package, deviceType);
}
}
示例13: ExtractLayouts
void ExtractLayouts(Package package, PackageDefinition manifest, string workingDirectory)
{
var localContentDirectory = Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.LocalContent);
fileSystem.EnsureDirectoryExists(localContentDirectory);
foreach (var layout in manifest.Layouts)
{
if (!layout.Name.StartsWith(AzureCloudServiceConventions.RoleLayoutPrefix))
continue;
var layoutDirectory = Path.Combine(localContentDirectory, layout.Name.Substring(AzureCloudServiceConventions.RoleLayoutPrefix.Length));
fileSystem.EnsureDirectoryExists(layoutDirectory);
foreach (var fileDefinition in layout.FileDefinitions)
{
var contentDefinition =
manifest.GetContentDefinition(fileDefinition.Description.DataContentReference);
var destinationFileName = Path.Combine(layoutDirectory, fileDefinition.FilePath.TrimStart('\\'));
ExtractPart(
package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
contentDefinition.Description.DataStorePath)),
destinationFileName);
}
}
}
示例14: CreateManifest
private static void CreateManifest(Package package)
{
using (var writer = XmlWriter.Create(GetPath(PackagePath + "\\" + "AppManifest.xaml"),
new XmlWriterSettings { OmitXmlDeclaration = true})) {
DeploymentParts.Parent.Save(writer);
}
CreateManifestPart(package);
}
示例15: InitializePackage
public void InitializePackage()
{
this.outputPackage = Package.Open(this.OutputFile,
System.IO.FileMode.Create,
System.IO.FileAccess.ReadWrite);
this.outputPackage.CreatePart(new Uri("/_index.htm", UriKind.Relative), "text/html");
}