您的位置:首页 > 编程语言 > C#

C# 对word (03、07)的相关操作

2012-06-21 13:57 447 查看
/// <summary>
/// 提供一组静态方法,用于操作 Office 文件的自定义属性
/// </summary>
public static class OfficeHelper
{
/// <summary>
/// 获取指定文件的自定义属性集
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <returns>自定义属性集</returns>
public static Dictionary<string, string> GetCustomProperties(string fileFullPath)
{
//创建存储结果的 Dictionary 字典表
Dictionary<string, string> fileProperties = new Dictionary<string, string>();

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return fileProperties;

//解析文件获取属性
ICustomProperty helper = GetHelper(fileFullPath);
fileProperties = helper.GetCustomProperties(fileFullPath);

//返回结果
return fileProperties;
}//end method

/// <summary>
/// 获取指定文件的自定义属性的值
/// </summary>
/// <param name="fileFullPath">指定的文件完全限定名称</param>
/// <param name="propertyName">自定义属性名称</param>
/// <returns>如果成功,返加文件属性的值;否则返回null</returns>
public static string GetCustomProperty(string fileFullPath, object propertyName)
{
//创建存储结果的字符串
string propertyValue = String.Empty;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return null;

//解析文件获取属性
ICustomProperty helper = GetHelper(fileFullPath);
propertyValue = helper.GetCustomProperty(fileFullPath, propertyName);

//返回结果
return propertyValue;
}//end method

/// <summary>
/// 添加指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件完全限定名称</param>
/// <param name="propertyName">自定义属性名称</param>
/// <param name="proertyValue">自定义属性值</param>
/// <returns>成功返回 true; 否则返回 false</returns>
public static bool AddCustomProperty(String fileFullPath, String propertyName, String propertyValue)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//移除文件中指定的属性
ICustomProperty helper = GetHelper(fileFullPath);
result = helper.AddCustomProperty(fileFullPath, propertyName, propertyValue);

//返回结果
return result;
}//end method

/// <summary>
/// 删除指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <param name="propertyName">自定义属性名称</param>
/// <returns>成功返回 true; 否则返回 false</returns>
public static bool RemoveCustomProperty(String fileFullPath, String propertyName)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//移除文件中指定的属性
ICustomProperty helper = GetHelper(fileFullPath);
result = helper.RemoveCustomProperty(fileFullPath, propertyName);

//返回结果
return result;
}//end method

/// <summary>
/// 修改指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <param name="propertyName">自定义属性名称</param>
/// <param name="propertyValue">自定义属性值</param>
/// <returns>成功返回 true; 否则返回 false</returns>
public static bool SetCustomProperty(String fileFullPath, String propertyName, String propertyValue)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//移除文件中指定的属性
ICustomProperty helper = GetHelper(fileFullPath);
result = helper.SetCustomProperty(fileFullPath, propertyName, propertyValue);

//返回结果
return result;
}//end method

/// <summary>
/// 根据文件类型创建相应属性解析器
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <returns>属性解析器</returns>
private static ICustomProperty GetHelper(String fileFullPath)
{
ICustomProperty helper = null;
//根据文件的格式(后缀:dot\doc\dotx\docx),采用不用解析器(DSOFile 解析器:dot\doc;OpenXml 解析器:dotx\docx)
String fileExt = System.IO.Path.GetExtension(fileFullPath);
String officeType = "2007";
if (fileExt.Equals(".dot", StringComparison.CurrentCultureIgnoreCase) || fileExt.Equals(".doc", StringComparison.CurrentCultureIgnoreCase))
{
officeType = "2003";
}

switch (officeType)
{
case "2007":
helper = new Office2007Helper();
break;
case "2003":
helper = new Office2003Helper();
break;
default:
break;
}//end switch

return helper;
}//end method

}//end class


internal class Office2007Helper
{
/// <summary>
/// 获取指定文件的自定义属性集
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <returns></returns>
public Dictionary<string, string> GetCustomProperties(string fileFullPath)
{
//创建存储结果的 Dictionary 字典表
Dictionary<string, string> fileProperties = new Dictionary<string, string>();

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return fileProperties;

String properties = String.Empty;
UnZipFile unZip = new UnZipFile();
String systemTempPath = System.Environment.GetEnvironmentVariable("TEMP");
CREATEPAPH: String currentBufferPath = System.IO.Path.Combine(systemTempPath, System.Guid.NewGuid().ToString("N"));

if (System.IO.Directory.Exists(currentBufferPath))
{
goto CREATEPAPH;

}
//创建目录用于提取属性文件
System.IO.Directory.CreateDirectory(currentBufferPath);
unZip.ExtractFile(fileFullPath, "docProps/custom.xml", currentBufferPath);

//如果成功提取属性文件则读取其内容
String propertyFileFullPath = System.IO.Path.Combine(currentBufferPath, "custom.xml");
if (System.IO.File.Exists(propertyFileFullPath))
{
//解析属性文件
System.Xml.XmlDocument propertyDocument = new System.Xml.XmlDocument();
propertyDocument.Load(propertyFileFullPath);
System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(propertyDocument.NameTable);
nsmgr.AddNamespace("cp", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
nsmgr.AddNamespace("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");

//解析属性集
System.Xml.XmlNodeList xmlNodes = propertyDocument.SelectNodes("//cp:Properties/cp:property", nsmgr);
foreach (System.Xml.XmlNode x in xmlNodes)
{
String key = x.Attributes["name"]== null ? String.Empty : x.Attributes["name"].Value.ToString();
if (String.IsNullOrEmpty(key))
{
continue;
}
String value = x.InnerText;
fileProperties.Add(key, value);
}

}
System.IO.Directory.Delete(currentBufferPath,true);
return fileProperties;
}//end method

/// <summary>
/// 获取指定文件的自定义属性的值
/// </summary>
/// <param name="fileFullPath">指定的文件完全限定名称</param>
/// <param name="propertyName">自定义属性名称</param>
/// <returns>如果成功,返加文件属性的值;否则返回null</returns>
public string GetCustomProperty(string fileFullPath, object propertyName)
{
//创建存储结果的字符串
string propertyValue = String.Empty;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return null;

String properties = String.Empty;
UnZipFile unZip = new UnZipFile();
String systemTempPath = System.Environment.GetEnvironmentVariable("TEMP");
CREATEPAPH: String currentBufferPath = System.IO.Path.Combine(systemTempPath, System.Guid.NewGuid().ToString("N"));

if (System.IO.Directory.Exists(currentBufferPath))
{
goto CREATEPAPH;

}
//创建目录用于提取属性文件
System.IO.Directory.CreateDirectory(currentBufferPath);
unZip.ExtractFile(fileFullPath, "docProps/custom.xml", currentBufferPath);

//如果成功提取属性文件则读取其内容
String propertyFileFullPath = System.IO.Path.Combine(currentBufferPath, "custom.xml");
if (System.IO.File.Exists(propertyFileFullPath))
{
//解析属性文件
System.Xml.XmlDocument propertyDocument = new System.Xml.XmlDocument();
propertyDocument.Load(propertyFileFullPath);
System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(propertyDocument.NameTable);
nsmgr.AddNamespace("cp", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
nsmgr.AddNamespace("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");

//解析属性集
System.Xml.XmlNodeList xmlNodes = propertyDocument.SelectNodes("//cp:Properties/cp:property", nsmgr);
foreach (System.Xml.XmlNode x in xmlNodes)
{
String key = x.Attributes["name"] == null ? String.Empty : x.Attributes["name"].Value.ToString();
if (String.IsNullOrEmpty(key))
{
continue;
}
String value = x.InnerText;
if (key.Equals(propertyName))
{
propertyValue = value;
break;
}
}

}
//清空资源
System.IO.Directory.Delete(currentBufferPath, true);

//返回结果
return propertyValue;
}//end method

/// <summary>
/// 添加指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件完全限定名称</param>
/// <param name="propertyName">自定义属性名称</param>
/// <param name="proertyValue">自定义属性值</param>
/// <returns>修改成功返回 true; 否则返回 false</returns>
public bool AddCustomProperty(String fileFullPath, String propertyName, String proertyValue)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return false;
try
{
String properties = String.Empty;
UnZipFile unZip = new UnZipFile();
String systemTempPath = System.Environment.GetEnvironmentVariable("TEMP");
CREATEPAPH: String currentBufferPath = System.IO.Path.Combine(systemTempPath, System.Guid.NewGuid().ToString("N"));

if (System.IO.Directory.Exists(currentBufferPath))
{
goto CREATEPAPH;

}
//创建目录用于提取属性文件
System.IO.Directory.CreateDirectory(currentBufferPath);
unZip.ExtractFile(fileFullPath, "docProps/custom.xml", currentBufferPath);

//如果成功提取属性文件则读取其内容
String propertyFileFullPath = System.IO.Path.Combine(currentBufferPath, "custom.xml");
Boolean firstCreateCustomProperties = false;
if (!System.IO.File.Exists(propertyFileFullPath))
{
//如果包中不存在自定义属性,则创建
CreateCustomXml(propertyFileFullPath);
firstCreateCustomProperties = true;
}
//解析属性文件
System.Xml.XmlDocument propertyDocument = new System.Xml.XmlDocument();
propertyDocument.Load(propertyFileFullPath);
System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(propertyDocument.NameTable);
nsmgr.AddNamespace("cp", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
nsmgr.AddNamespace("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");

//解析属性集
System.Xml.XmlNodeList xmlNodes = propertyDocument.SelectNodes("//cp:Properties/cp:property", nsmgr);

Boolean isExists = false;
foreach (System.Xml.XmlNode x in xmlNodes)
{
String key = x.Attributes["name"] == null ? String.Empty : x.Attributes["name"].Value.ToString();
if (String.IsNullOrEmpty(key))
{
continue;
}
String value = x.InnerText;
if (key.Equals(propertyName))
{
System.Xml.XmlNode propertyValueNode = x.FirstChild;//.CreateElement("vt", "lpwstr", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
propertyValueNode.InnerText = value;

isExists = true;
break;
}
}

if (!isExists)
{
System.Xml.XmlNode propertiesNode = propertyDocument.SelectSingleNode("//cp:Properties", nsmgr);
//创建自定义属性元素
System.Xml.XmlElement propertyNode = propertyDocument.CreateElement("", "property", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");

//创建属性: FMTID_UserDefinedPropertie=D5CDD505-2E9C-101B-9397-08002B2CF9AE
System.Xml.XmlAttribute fmtidAttribute = propertyDocument.CreateAttribute("fmtid");
fmtidAttribute.Value = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";

//创建属性: pid=2
System.Xml.XmlNodeList propertyNodeList = propertyDocument.SelectNodes("//cp:Properties/cp:property", nsmgr);
//rId4

Int32 maxId = 2;
foreach (System.Xml.XmlNode r in propertyNodeList)
{
String pid = r.Attributes["pid"].Value;
if (!String.IsNullOrEmpty(pid))
{
Int32 v = Convert.ToInt32(pid);
if (v >= maxId)
{
maxId = v + 1;
}
}
}

System.Xml.XmlAttribute pidAttribute = propertyDocument.CreateAttribute("pid");
pidAttribute.Value = maxId.ToString();

//创建属性:name
System.Xml.XmlAttribute nameAttribute = propertyDocument.CreateAttribute("name");
nameAttribute.Value = propertyName;

//创建字符值元素:
System.Xml.XmlNode propertyValueNode = propertyDocument.CreateElement("vt", "lpwstr", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
propertyValueNode.InnerText = proertyValue;

//添加字符值元素:
propertyNode.AppendChild(propertyValueNode);
//添加属性: fmtid
propertyNode.Attributes.Append(fmtidAttribute);
//添加属性: pid
propertyNode.Attributes.Append(pidAttribute);
//添加属性:name
propertyNode.Attributes.Append(nameAttribute);
propertiesNode.AppendChild(propertyNode);
}

propertyDocument.Save(propertyFileFullPath);

//保存临时目录中的文件到源文件包中
ZipFile zip = new ZipFile();
zip.UpdateZipFile(fileFullPath, propertyFileFullPath, @"docProps/custom.xml");

if (firstCreateCustomProperties)
{
#region 更新文件[Content_Types].xml
//如果是第一次创建自定义属性,则必须更新文件:[Content_Types].xml
unZip.ExtractFile(fileFullPath, "[Content_Types].xml", currentBufferPath);
String contentTypesFileFullPath = System.IO.Path.Combine(currentBufferPath, "[Content_Types].xml");
System.Xml.XmlDocument contentTypesDocument = new System.Xml.XmlDocument();
contentTypesDocument.Load(contentTypesFileFullPath);
System.Xml.XmlNamespaceManager ctNsmgr = new System.Xml.XmlNamespaceManager(propertyDocument.NameTable);
ctNsmgr.AddNamespace("ct", "http://schemas.openxmlformats.org/package/2006/content-types");

//解析属性集
System.Xml.XmlNode xmlNode = contentTypesDocument.SelectSingleNode("//ct:Types/ct:Override[@PartName=" + "'/docProps/custom.xml']", ctNsmgr);
if (xmlNode == null)
{
//创建自定义属性相关元素
xmlNode = contentTypesDocument.CreateElement("", "Override", "http://schemas.openxmlformats.org/package/2006/content-types");

//创建属性: PartName
System.Xml.XmlAttribute partNameAttribute = contentTypesDocument.CreateAttribute("PartName");
partNameAttribute.Value = @"/docProps/custom.xml";

//创建属性:ContentType
System.Xml.XmlAttribute contentTypeAttribute = contentTypesDocument.CreateAttribute("ContentType");
contentTypeAttribute.Value = "application/vnd.openxmlformats-officedocument.custom-properties+xml";

//添加属性:PartName & ContentType
xmlNode.Attributes.Append(partNameAttribute);
xmlNode.Attributes.Append(contentTypeAttribute);

}

System.Xml.XmlNode typeNode = contentTypesDocument.SelectSingleNode("//ct:Types", ctNsmgr);
typeNode.AppendChild(xmlNode);
contentTypesDocument.Save(contentTypesFileFullPath);
ZipFile zipPackage = new ZipFile();
zipPackage.UpdateZipFile(fileFullPath, contentTypesFileFullPath, @"[Content_Types].xml");
#endregion 更新文件[Content_Types].xml

#region 更新文件:_rels\.rels
//如果是第一次创建自定义属性,则必须更新文件:_rels\.rels
unZip.ExtractFile(fileFullPath, "_rels/.rels", currentBufferPath);
String rootRelsFileFullPath = System.IO.Path.Combine(currentBufferPath, ".rels");
System.Xml.XmlDocument rootRelsDocument = new System.Xml.XmlDocument();
rootRelsDocument.Load(rootRelsFileFullPath);
System.Xml.XmlNamespaceManager relsNsmgr = new System.Xml.XmlNamespaceManager(rootRelsDocument.NameTable);
relsNsmgr.AddNamespace("rs", "http://schemas.openxmlformats.org/package/2006/relationships");

//解析属性集
System.Xml.XmlNode relsNode = rootRelsDocument.SelectSingleNode("//rs:Relationships/rs:Relationship[@Target=" + "'docProps/custom.xml']", relsNsmgr);
if (relsNode == null)
{
System.Xml.XmlNodeList relsNodeList = rootRelsDocument.SelectNodes("//rs:Relationships/rs:Relationship", relsNsmgr);
//rId4

Int32 maxId = 1;
foreach (System.Xml.XmlNode r in relsNodeList)
{
String rId = r.Attributes["Id"].Value;
if (!String.IsNullOrEmpty(rId) && rId.StartsWith("rId"))
{
Int32 v = Convert.ToInt32(rId.Substring(3));
if (v >= maxId)
{
maxId = v + 1;
}
}
}

//创建自定义属性相关元素
relsNode = rootRelsDocument.CreateElement("", "Relationship", "http://schemas.openxmlformats.org/package/2006/relationships");

//创建属性: Id
System.Xml.XmlAttribute idAttribute = rootRelsDocument.CreateAttribute("Id");
idAttribute.Value = String.Format("rId{0}", maxId);

//创建属性:Type
System.Xml.XmlAttribute typeAttribute = rootRelsDocument.CreateAttribute("Type");
typeAttribute.Value = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";

//创建属性:Target
System.Xml.XmlAttribute targetAttribute = rootRelsDocument.CreateAttribute("Target");
targetAttribute.Value = "docProps/custom.xml";

//添加属性:Id & Type & Target
relsNode.Attributes.Append(idAttribute);
relsNode.Attributes.Append(typeAttribute);
relsNode.Attributes.Append(targetAttribute);

}

System.Xml.XmlNode relationshipsNode = rootRelsDocument.SelectSingleNode("//rs:Relationships", relsNsmgr);
relationshipsNode.AppendChild(relsNode);
rootRelsDocument.Save(rootRelsFileFullPath);
ZipFile zipPackages = new ZipFile();
zipPackages.UpdateZipFile(fileFullPath, rootRelsFileFullPath, @"_rels/.rels");
#endregion 更新文件:_rels\.rels
}

result = true;
//清空资源
System.IO.Directory.Delete(currentBufferPath, true);
}
catch
{
result = false;
}

//返回结果
return result;
}//end method
private Boolean CreateCustomXml(String filePath)
{
Boolean result = false;
//创建自定义属性XML文档
System.Xml.XmlDocument customXmlDoc = new System.Xml.XmlDocument();
//创建文档声明
System.Xml.XmlDeclaration xd = customXmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
//创建属性根结构
System.Xml.XmlElement propertiesRoot = customXmlDoc.CreateElement("Properties");
//创建属性:xmlns
System.Xml.XmlAttribute customAttribute = customXmlDoc.CreateAttribute("xmlns");
customAttribute.Value = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
//创建属性:xmlns:vt
System.Xml.XmlAttribute vtAttribute = customXmlDoc.CreateAttribute("xmlns:vt");
vtAttribute.Value = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes";
propertiesRoot.Attributes.Append(customAttribute);
propertiesRoot.Attributes.Append(vtAttribute);
//添加文档声明到XML文档
customXmlDoc.AppendChild(xd);
//添加根结点
customXmlDoc.AppendChild(propertiesRoot);

//保存到文件
customXmlDoc.Save(filePath);

result = true;

return result;
}
/// <summary>
/// 删除指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <param name="propertyName">自定义属性名称</param>
/// <returns>删除成功返回 true; 否则返回 false</returns>
public bool RemoveCustomProperty(String fileFullPath, String propertyName)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//创建目录用于提取属性文件
String systemTempPath = System.Environment.GetEnvironmentVariable("TEMP");
CREATEPAPH: String currentBufferPath = System.IO.Path.Combine(systemTempPath, System.Guid.NewGuid().ToString("N"));

if (System.IO.Directory.Exists(currentBufferPath))
{
goto CREATEPAPH;

}

System.IO.Directory.CreateDirectory(currentBufferPath);

//提取文件到临时目录
UnZipFile unZip = new UnZipFile();
unZip.ExtractFile(fileFullPath, "docProps/custom.xml", currentBufferPath);

//如果成功提取属性文件则读取其内容
String propertyFileFullPath = System.IO.Path.Combine(currentBufferPath, "custom.xml");
if (System.IO.File.Exists(propertyFileFullPath))
{
//解析属性文件
System.Xml.XmlDocument propertyDocument = new System.Xml.XmlDocument();
propertyDocument.Load(propertyFileFullPath);
System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(propertyDocument.NameTable);
nsmgr.AddNamespace("cp", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
nsmgr.AddNamespace("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");

//解析属性集
System.Xml.XmlNodeList xmlNodes = propertyDocument.SelectNodes("//cp:Properties/cp:property", nsmgr);
Boolean deleted = false;
foreach (System.Xml.XmlNode x in xmlNodes)
{
String key = x.Attributes["name"] == null ? String.Empty : x.Attributes["name"].Value.ToString();
if (String.IsNullOrEmpty(key))
{
continue;
}
String value = x.InnerText;
if (key.Equals(propertyName))
{
x.ParentNode.RemoveChild(x);
propertyDocument.Save(propertyFileFullPath);
deleted = true;
break;
}
}

if (deleted)
{
//保存临时目录中的文件到源文件包中
ZipFile zip = new ZipFile();
zip.UpdateZipFile(fileFullPath, propertyFileFullPath, @"docProps/custom.xml");
}

}

//清空资源
System.IO.Directory.Delete(currentBufferPath, true);

//返回结果
return result;
}//end method

/// <summary>
/// 修改指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <param name="propertyName">自定义属性名称</param>
/// <param name="propertyValue">自定义属性值</param>
/// <returns>删除成功返回 true; 否则返回 false</returns>
public bool SetCustomProperty(String fileFullPath, String propertyName, String propertyValue)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//创建目录用于提取属性文件
String systemTempPath = System.Environment.GetEnvironmentVariable("TEMP");
CREATEPAPH: String currentBufferPath = System.IO.Path.Combine(systemTempPath, System.Guid.NewGuid().ToString("N"));

if (System.IO.Directory.Exists(currentBufferPath))
{
goto CREATEPAPH;

}

System.IO.Directory.CreateDirectory(currentBufferPath);

//提取文件到临时目录
UnZipFile unZip = new UnZipFile();
unZip.ExtractFile(fileFullPath, "docProps/custom.xml", currentBufferPath);

//如果成功提取属性文件则读取其内容
String propertyFileFullPath = System.IO.Path.Combine(currentBufferPath, "custom.xml");
if (System.IO.File.Exists(propertyFileFullPath))
{
//解析属性文件
System.Xml.XmlDocument propertyDocument = new System.Xml.XmlDocument();
propertyDocument.Load(propertyFileFullPath);
System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(propertyDocument.NameTable);
nsmgr.AddNamespace("cp", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
nsmgr.AddNamespace("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");

//解析属性集
System.Xml.XmlNodeList xmlNodes = propertyDocument.SelectNodes("//cp:Properties/cp:property", nsmgr);
Boolean deleted = false;
foreach (System.Xml.XmlNode x in xmlNodes)
{
String key = x.Attributes["name"] == null ? String.Empty : x.Attributes["name"].Value.ToString();
if (String.IsNullOrEmpty(key))
{
continue;
}
String value = x.InnerText;
if (key.Equals(propertyName))
{
//创建字符值元素:
System.Xml.XmlNode propertyValueNode = x.FirstChild;//.CreateElement("vt", "lpwstr", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
propertyValueNode.InnerText = propertyValue;

propertyDocument.Save(propertyFileFullPath);
deleted = true;
break;
}
}

if (deleted)
{
//保存临时目录中的文件到源文件包中
ZipFile zip = new ZipFile();
zip.UpdateZipFile(fileFullPath, propertyFileFullPath, @"docProps/custom.xml");
}
}

//清空资源
System.IO.Directory.Delete(currentBufferPath, true);

//返回结果
return result;
}//end method

}//end class


internal class Office2003Helper
{

/// <summary>
/// 获取指定文件的自定义属性集
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <returns>自定义属性集</returns>
public Dictionary<string, string> GetCustomProperties(string fileFullPath)
{
//创建存储结果的 Dictionary 字典表
Dictionary<string, string> fileProperties = new Dictionary<string, string>();

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return fileProperties;

//创建文件属性对象
OleDocumentPropertiesClass document = new DSOFile.OleDocumentPropertiesClass();
//以只读方式关联文件
Boolean openReadOnly = true;
document.Open(fileFullPath, openReadOnly, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess);
//读取文件自定义属性
foreach (CustomProperty p in document.CustomProperties)
{
if (p.Type != dsoFilePropertyType.dsoPropertyTypeUnknown && p.Name != null)
{
fileProperties.Add(p.Name, p.get_Value().ToString());
}
}
//释放相关资源
document.Close(false);

//返回结果
return fileProperties;
}//end method

/// <summary>
/// 获取指定文件的自定义属性的值
/// </summary>
/// <param name="fileFullPath">指定的文件完全限定名称</param>
/// <param name="propertyName">自定义属性名称</param>
/// <returns>如果成功,返加文件属性的值;否则返回null</returns>
public string GetCustomProperty(string fileFullPath, object propertyName)
{
//创建存储结果的字符串
string propertyValue = String.Empty;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return null;

//创建文件属性对象
OleDocumentPropertiesClass document = new DSOFile.OleDocumentPropertiesClass();
//以只读方式关联文件
Boolean openReadOnly = true;
document.Open(fileFullPath, openReadOnly, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess);
//读取文件自定义属性
foreach (CustomProperty p in document.CustomProperties)
{
//判断指定名称的属性值是否存在
if (p.Type != dsoFilePropertyType.dsoPropertyTypeUnknown && p.Name.Equals(propertyName))
{
propertyValue = p.get_Value().ToString();
break;
}
}
//释放相关资源
document.Close(false);

//返回结果
return propertyValue;
}//end method

/// <summary>
/// 添加指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件完全限定名称</param>
/// <param name="propertyName">自定义属性名称</param>
/// <param name="proertyValue">自定义属性值</param>
/// <returns>成功返回 true; 否则返回 false</returns>
public bool AddCustomProperty(String fileFullPath, String propertyName, String proertyValue)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//创建文件属性对象
OleDocumentPropertiesClass document = new DSOFile.OleDocumentPropertiesClass();
//以只读方式关联文件
Boolean openReadOnly = false;
document.Open(fileFullPath, openReadOnly, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess);
//读取文件自定义属性
Int32 oldCount = document.CustomProperties.Count;
object prop = proertyValue;
//如果存在此属性,则修改其值;否则创建属性
Boolean isExist = false;
foreach (CustomProperty p in document.CustomProperties)
{
//判断指定名称的属性值是否存在
if (p.Type != dsoFilePropertyType.dsoPropertyTypeUnknown && p.Name.Equals(propertyName))
{
p.set_Value(ref prop);
isExist = true;
break;
}

}
Int32 newCount = 0;
if (!isExist)
{
document.CustomProperties.Add(propertyName, ref prop);
newCount= document.CustomProperties.Count;
}
try
{
if (newCount == oldCount + 1 || isExist)
{

if (document.IsDirty && !document.IsReadOnly)
{
document.Save();
}
result = true;
}
}
catch (Exception ex)
{

result = false;
}

//释放相关资源
document.Close(true);

//返回结果
return result;
}//end method

/// <summary>
/// 删除指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <param name="propertyName">自定义属性名称</param>
/// <returns>成功返回 true; 否则返回 false</returns>
public bool RemoveCustomProperty(String fileFullPath, String propertyName)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//创建文件属性对象
OleDocumentPropertiesClass document = new DSOFile.OleDocumentPropertiesClass();
//以只读方式关联文件
Boolean openReadOnly = false;
document.Open(fileFullPath, openReadOnly, DSOFile.dsoFileOpenOptions.dsoOptionUseMBCStringsForNewSets);
//读取文件自定义属性
Int32 oldCount = document.CustomProperties.Count;
Int32 newCount = 0;
for (int i = 0; i < oldCount; i++)
{
CustomProperty p = document.CustomProperties[i];
if (p.Name != null && p.Name.Equals(propertyName))
{

p.Remove();
newCount = document.CustomProperties.Count;
//p = null;
break;
}
}

try
{
if (newCount == oldCount - 1)
{

if (document.IsDirty && !document.IsReadOnly)
{
document.Save();
}
result = true;
}
}
catch (Exception ex)
{

result = false;
}

//释放相关资源
document.Close(true);

//返回结果
return result;
}//end method

/// <summary>
/// 修改指定文件的自定义属性
/// </summary>
/// <param name="fileFullPath">指定的文件名</param>
/// <param name="propertyName">自定义属性名称</param>
/// <param name="propertyValue">自定义属性值</param>
/// <returns>成功返回 true; 否则返回 false</returns>
public bool SetCustomProperty(String fileFullPath, String propertyName, String propertyValue)
{
bool result = false;

//如果指定的文件不存在,则返回
if (String.IsNullOrEmpty(fileFullPath) || !System.IO.File.Exists(fileFullPath))
return result;

//创建文件属性对象
OleDocumentPropertiesClass document = new DSOFile.OleDocumentPropertiesClass();
//以只读方式关联文件
Boolean openReadOnly = false;
document.Open(fileFullPath, openReadOnly, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess);
//定位并修改文件自定义属性
foreach (CustomProperty p in document.CustomProperties)
{
if (p.Name != null && p.Name.Equals(propertyName))
{
object prop=(object)propertyValue;
p.set_Value(ref prop);

break;
}
}

try
{
if (document.IsDirty && !document.IsReadOnly)
{
document.Save();
}
result = true;

}
catch (Exception ex)
{

result = false;
}

//释放相关资源
document.Close(true);

//返回结果
return result;
}//end method

}//end class









                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: