最主要是这句dynamic comObject = Activator.CreateInstance(Type.GetTypeFromProgID(“kwps.Application”));
/*
- 由SharpDevelop创建。
- 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
*/
using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Text.RegularExpressions;
namespace conert
{
///
/// Description of Class3.
///
public class Class3
{
const bool isVisible = false;
public Class3()
{
}
public void method1(String infile,String outfile){
string extension = Path.GetExtension(infile);
if (extension != null && Regex.IsMatch(extension, @"\.(doc|docx)$", RegexOptions.IgnoreCase))
{
Console.WriteLine(infile+" is a word file.");
}
else
{
Console.WriteLine("This is not a word file. 取消执行");
return ;
}
bool fileExists = File.Exists(infile);
Console.WriteLine("File.Exists:"+fileExists);
if(!fileExists){ throw new Exception("文件不存在");}
dynamic word = Activator.CreateInstance(Type.GetTypeFromProgID("kwps.Application"));
word.Visible=isVisible;
word.Documents.Open(infile);
// Console.WriteLine(word.Documents.Open(infile));
dynamic doc=word.ActiveDocument ;
//处理编辑保护
int isProtect=doc.ProtectionType;
Console.WriteLine("protect: " + doc.ProtectionType );
if (-1 != isProtect) {
try {
doc.Unprotect("");
} catch (COMException comEx) {
// Console.WriteLine("C调用失败: " + comEx.Message);
Console.WriteLine("C调用失败码: " + comEx.ErrorCode);// -2146825275 无密码
// Console.WriteLine("C调用失败码: " + comEx.Data);
// throw comEx;
//-2146825274 密码不正确
if (comEx.ErrorCode == -2146825274) {
doc.Close();
word.Quit();
throw comEx;
}
}
}//处理编辑保护 end
try
{
dynamic section=doc.Sections.Item(1);
for(int i=1;i<=section.Headers.count;i++){
if(null!=section.Headers.Item(i).Range)
section.Headers.Item(i).Range.delete();
}
for(int i=1;i<=section.Footers.count;i++){
if(null!=section.Footers.Item(i))
section.Footers.Item(i).Range.delete();
}
doc.SaveAs(outfile);//SaveAs
// doc.Save();
doc.Close();
word.Quit();
}
catch (COMException comEx)
{
Console.WriteLine("C调用失败: " + comEx.Message);
throw comEx;
}
}
static void Main2(string[] args)
{
dynamic comObject = Activator.CreateInstance(Type.GetTypeFromProgID("kwps.Application"));
try
{
Console.WriteLine(comObject.SomeMethod());
}
catch (COMException comEx)
{
Console.WriteLine("COM调用失败: " + comEx.Message);
}
}
}
}
8985

被折叠的 条评论
为什么被折叠?



