2011年到了,在前几天的“2010岁末小记”中给自己定下了一个计划,其中有一条就是“每周至少写一篇技术博客。用博客的方式来督促自己学习和进步,记下学习的新知识和积累的知识点,构建自己的知识库。”。园子里高手很多,MVP就有好几位,看他们的文章真有“看君一博文,胜读四年书”之感。曾经对委托、事件云里雾里的我看了张子阳的“C#中的委托和事件”后终于明白了很多,园子里像这样的好文章还有很多,作为菜鸟我真的获益匪浅。

  虽然自己现在水平很差,但高手都是从菜鸟成长起来的,因此我坚信只要努力学习,每天都有收获和进步,逐渐提高自己的编程水平,总有一天也能厚积薄发,写出一些比较好的博文与大家分享,帮助新手进步。作为新年第一篇博文,我打算写一个博客备份系统系列文章与园友们分享,晒晒自己的代码,非常欢迎大家提出意见和建议。

  本文作为此系列的开篇,只写几个后面要用到的重要的类,PDF、Word、TXT文件操作类,其中Word、TXT文件操作类网上很多,这两个类的代码我只直接贴出来,重点说一下PDF文件操作类。

  一、PDF文件操作类

  本文PDF文件操作类用iTextSharp控件,这是一个开源项目(http://sourceforge.net/projects/itextsharp/),园子里也有这方面的文章,我的PDF操作类只是做了一点封装,使使用起来更方便。在贴出代码前先对其中几个比较关键的地方作一下说明。

  1、文档的创建

  PDF文档的创建是实例化一个Document对像,有三个构造函数:

publicDocument();publicDocument(Rectangle pageSize);publicDocument(Rectangle pageSize,floatmarginLeft,floatmarginRight,floatmarginTop,floatmarginBottom);

  第一个是默认大小,第二个是按给定的大小创建文档,第三个就是按给定的大小创建文档,并且文档内容离左、右、上、下的距离。其中的Rectangle也是iTextSharp中的一个表示矩形的类,这里只用来表示大小。不过要注意的是在向文档里写内容之前还要调用GetInstance方法哦,这个方法传进去一些文档相关信息(如路径,打开方式等)。

  2、字体的设置

  PDF文件字体在iTextSharp中有两个类,BaseFont和Font,BaseFont是一个抽象类,BaseFont和Font的构造函数如下:

  BaseFont:  

publicstaticBaseFont CreateFont();publicstaticBaseFont CreateFont(PRIndirectReference fontRef);publicstaticBaseFont CreateFont(stringname,stringencoding,boolembedded);publicstaticBaseFont CreateFont(stringname,stringencoding,boolembedded,boolforceRead);publicstaticBaseFont CreateFont(stringname,stringencoding,boolembedded,boolcached,byte[] ttfAfm,byte[] pfb);publicstaticBaseFont CreateFont(stringname,stringencoding,boolembedded,boolcached,byte[] ttfAfm,byte[] pfb,boolnoThrow);publicstaticBaseFont CreateFont(stringname,stringencoding,boolembedded,boolcached,byte[] ttfAfm,byte[] pfb,boolnoThrow,boolforceRead);

  默认的构造函数用的是英文字体,如果想用中文一般用的是第三个构造函数,这三个参数前两个意思是字体名子或字体资源路径,第三个参数我也没弄明白是什么意思。如果用字体名子其实用的是这个DLL内置字体,如果用字体资源名子可以用系统字体存放路径,如“C:\Windows\Fonts\SIMHEI.TTF”(windows系统),也可以把字体文件放在应用程序目录,然后取这个路径。

  Font:

publicFont();publicFont(BaseFont bf);publicFont(Font other);publicFont(Font.FontFamily family);publicFont(BaseFont bf,floatsize);publicFont(Font.FontFamily family,floatsize);publicFont(BaseFont bf,floatsize,intstyle);publicFont(Font.FontFamily family,floatsize,intstyle);publicFont(BaseFont bf,floatsize,intstyle, BaseColor color);publicFont(Font.FontFamily family,floatsize,intstyle, BaseColor color);

  一般用的是第五个构造函数,也就是从BaseFont创建,然后设置字体大小。因为iTestSharp在添加文字时字体参数用的都是Font,因些一般的做法是先创建BaseFont对象,再用这个对象加上大小来实例化Font对象。

  3、添加段落

  iTextSharp对段落分了三个级别,从小到大依次为Chunk、Phrase、Paragraph。Chunk : 块,PDF文档中描述的最小原子元,Phrase : 短语,Chunk的集合,Paragraph : 段落,一个有序的Phrase集合。你可以简单地把这三者理解为字符,单词,文章的关系。

  Document对象添加内容的方法为:

publicvirtualboolAdd(IElement element);

  Chunk、Phrase实现了IElement接口,Paragraph继承自Phrase,因些Document可直接添加这三个对象。

  Paragraph的构造函数是:

publicParagraph();publicParagraph(Chunk chunk);publicParagraph(floatleading);publicParagraph(Phrase phrase);publicParagraph(stringstr);publicParagraph(floatleading, Chunk chunk);publicParagraph(floatleading,stringstr);publicParagraph(stringstr, Font font);publicParagraph(floatleading,stringstr, Font font);

  大家可以看到Chunk、Phrase都可以实例化Paragraph,不过我用的比较多的是倒数第二个。当然了,Paragraph还有一些属性可以让我们给段落设定一些格式,比如对齐方式,段前空行数,段后空行数,行间距等。 这些属性如下:

protectedintalignment;protectedfloatindentationLeft;protectedfloatindentationRight;protectedboolkeeptogether;protectedfloatmultipliedLeading;protectedfloatspacingAfter;protectedfloatspacingBefore;

  略作解释:alignmant为对齐方式(1为居中,0为居左,2为居右),indentationLeft为左缩进,indentationRight为右缩进,keeptogether保持在一起(常用在对内容绝对定位),multipliedLeading为行间距,spacingAfter为段前空行数,spacingBefore为段后空行数。

  4、内部链接和外部链接

  链接在iTextSharp中有Anchor对象,它有两个属性,name和reference,name自然就是链接的名称了,reference就是链接的地址了,如果是外部链接reference直接就是一个网址,如果是内部链接,就跟html中的锚一样,用'#'加上name名,示例如下:

//外部链接示例Anchor anchor=newAnchor("博客园", font);
            anchor.Reference
="http://www.cnblogs.com";
            anchor.Name
="博客园";//内部链接示例Anchor anc1=newAnchor("This is an internal link test");
            anc1.Name
="test";
            Anchor anc2
=newAnchor("Click here to jump to the internal link test");
            anc2.Reference
="#test";

  5、插入图片

  在PDF中插入图片用的是iTextSharp中的Image类。这个类的构造函数很简单:

publicImage(Image image);publicImage(Uri url);

  常用的就是用图片的Uri来实例化一个图片。因为这个数继承自Rectangle,而Rectangle又实现了IElement接口,因些可以直接将图片添加到文档中。Image有很多属性用来控制格式,不过常用的也就是对齐方式(Alignment),图片大小的控制了。不过值得一提的就是ScaleAbsolute方法:

publicvoidScaleAbsolute(floatnewWidth,floatnewHeight);

  看参数就知道是给图片重新设定宽度和高度的,我的做法是如果图片宽度大于文档宽度就按比例缩小,否则不处理:

///<summary>///添加图片///</summary>///<param name="path">图片路径</param>///<param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>///<param name="newWidth">图片宽(0为默认值,如果宽度大于页宽将按比率缩放)</param>///<param name="newHeight">图片高</param>publicvoidAddImage(stringpath,intAlignment,floatnewWidth,floatnewHeight)
        {
            Image img
=Image.GetInstance(path);
            img.Alignment
=Alignment;if(newWidth!=0)
            {
                img.ScaleAbsolute(newWidth, newHeight);
            }
else{if(img.Width>PageSize.A4.Width)
                {
                    img.ScaleAbsolute(rect.Width, img.Width
*img.Height/rect.Height);
                }
            }
            document.Add(img);
        }

  其中的rect是我定义的一个文档大小属性。

  好了,下面就贴出我的PDF文档操作类吧。为了达到封装的目地(这里说的封装意思是调用的类可以不引用iTextSharp这个DLL),我在传参过程中做了一点更改。如设置页面大小时Document的构造函数中提供了用Rectangle对象实例化,但因为这个类是iTextSharp中的,因此我改为传一个字符串(如"A4"),根据这个字符串实例化一个Rectangle对象,再来设置页面大小,其它地方类似。

PDF操作类

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingiTextSharp.text;usingiTextSharp.text.pdf;usingSystem.IO;namespaceBlogBakLib
{
///<summary>///PDF文档操作类///作者:天行健,自强不息(http://www.cnblogs.com/durongjian///创建日期:2011年1月5日///</summary>publicclassPDFOperation
    {
//文档对象privateDocument document;//文档大小privateRectangle rect;//字体privateBaseFont basefont;privateFont font;///<summary>///构造函数///</summary>publicPDFOperation()
        {
            rect
=PageSize.A4;
            document
=newDocument(rect);
        }
///<summary>///构造函数///</summary>///<param name="type">页面大小(如"A4")</param>publicPDFOperation(stringtype)
        {
            SetPageSize(type);
            document
=newDocument(rect);
        }
///<summary>///构造函数///</summary>///<param name="type">页面大小(如"A4")</param>///<param name="marginLeft">内容距左边框距离</param>///<param name="marginRight">内容距右边框距离</param>///<param name="marginTop">内容距上边框距离</param>///<param name="marginBottom">内容距下边框距离</param>publicPDFOperation(stringtype,floatmarginLeft,floatmarginRight,floatmarginTop,floatmarginBottom)
        {
            SetPageSize(type);
            document
=newDocument(rect,marginLeft,marginRight,marginTop,marginBottom);
        }
///<summary>///构造函数///</summary>///<param name="type">页面大小(如"A4")</param>publicPDFOperation(stringtype)
        {
            SetPageSize(type);
            document
=newDocument(rect);
        }
///<summary>///设置页面大小///</summary>///<param name="type">页面大小(如"A4")</param>publicvoidSetPageSize(stringtype)
        {
switch(type.Trim())
            {
case"A4":
                    rect
=PageSize.A4;break;case"A8":
                    rect
=PageSize.A8;break;
            }
        }
///<summary>///设置字体///</summary>publicvoidSetBaseFont(stringpath)
        {
            basefont
=BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
///<summary>///设置字体///</summary>///<param name="size">字体大小</param>publicvoidSetFont(floatsize)
        {
            font
=newFont(basefont, size);
        }
///<summary>///实例化文档///</summary>///<param name="os">文档相关信息(如路径,打开方式等)</param>publicvoidGetInstance(Stream os)
        {
            PdfWriter.GetInstance(document, os);
        }
///<summary>///打开文档对象///</summary>///<param name="os">文档相关信息(如路径,打开方式等)</param>publicvoidOpen(Stream os)
        {
            GetInstance(os);
            document.Open();
        }
///<summary>///关闭打开的文档///</summary>publicvoidClose()
        {
            document.Close();
        }
///<summary>///添加段落///</summary>///<param name="content">内容</param>///<param name="fontsize">字体大小</param>publicvoidAddParagraph(stringcontent,floatfontsize)
        {
            SetFont(fontsize);
            Paragraph pra
=newParagraph(content,font);
            document.Add(pra);
        }
///<summary>///添加段落///</summary>///<param name="content">内容</param>///<param name="fontsize">字体大小</param>///<param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>///<param name="SpacingAfter">段后空行数(0为默认值)</param>///<param name="SpacingBefore">段前空行数(0为默认值)</param>///<param name="MultipliedLeading">行间距(0为默认值)</param>publicvoidAddParagraph(stringcontent,floatfontsize,intAlignment,floatSpacingAfter,floatSpacingBefore,floatMultipliedLeading)
        {
            SetFont(fontsize);
            Paragraph pra
=newParagraph(content, font);
            pra.Alignment
=Alignment;if(SpacingAfter!=0)
            {
                pra.SpacingAfter
=SpacingAfter;
            }
if(SpacingBefore!=0)
            {
                pra.SpacingBefore
=SpacingBefore;
            }
if(MultipliedLeading!=0)
            {
                pra.MultipliedLeading
=MultipliedLeading;
            }
            document.Add(pra);
        }
///<summary>///添加链接///</summary>///<param name="Content">链接文字</param>///<param name="FontSize">字体大小</param>///<param name="Reference">链接地址</param>publicvoidAddAnchorReference(stringContent,floatFontSize,stringReference)
        {
            SetFont(FontSize);
            Anchor auc
=newAnchor(Content, font);
            auc.Reference
=Reference;
            document.Add(auc);
        }
///<summary>///添加链接点///</summary>///<param name="Content">链接文字</param>///<param name="FontSize">字体大小</param>///<param name="Name">链接点名</param>publicvoidAddAnchorName(stringContent,floatFontSize,stringName)
        {
            SetFont(FontSize);
            Anchor auc
=newAnchor(Content, font);
            auc.Name
=Name;
            document.Add(auc);
        }
///<summary>///添加图片///</summary>///<param name="path">图片路径</param>///<param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>///<param name="newWidth">图片宽(0为默认值,如果宽度大于页宽将按比率缩放)</param>///<param name="newHeight">图片高</param>publicvoidAddImage(stringpath,intAlignment,floatnewWidth,floatnewHeight)
        {
            Image img
=Image.GetInstance(path);
            img.Alignment
=Alignment;if(newWidth!=0)
            {
                img.ScaleAbsolute(newWidth, newHeight);
            }
else{if(img.Width>PageSize.A4.Width)
                {
                    img.ScaleAbsolute(rect.Width, img.Width
*img.Height/rect.Height);
                }
            }
            document.Add(img);
        }
    }
}

  好了,PDF操作类就写到这儿吧!因为本人编程是自学的,在编码规范方面可能做的不好,大家对这个类中的代码有什么改进意见请在评论中指出来哦!

  二、WORD文档操作类

  这个就不说了,直接贴代码:  

WORD操作类

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Drawing;usingSystem.IO;namespaceBlogMoveLib   
{
publicclassWordOperation   
    {
privateMicrosoft.Office.Interop.Word.ApplicationClass oWordApplic;privateMicrosoft.Office.Interop.Word.Document oDoc;objectmissing=System.Reflection.Missing.Value;publicMicrosoft.Office.Interop.Word.ApplicationClass WordApplication   
        {
get{returnoWordApplic; }   
        }
publicWordOperation()   
        {     
            oWordApplic
=newMicrosoft.Office.Interop.Word.ApplicationClass();   
        }
publicWordOperation(Microsoft.Office.Interop.Word.ApplicationClass wordapp)   
        {   
            oWordApplic
=wordapp;   
        }
#region文件操作//Open a file (the file must exists) and activate itpublicvoidOpen(stringstrFileName)   
        {
objectfileName=strFileName;objectreadOnly=false;objectisVisible=true;   
  
            oDoc
=oWordApplic.Documents.Open(reffileName,refmissing,refreadOnly,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refisVisible,refmissing,refmissing,refmissing,refmissing);   
  
            oDoc.Activate();   
        }
//Open a new documentpublicvoidOpen()   
        {   
            oDoc
=oWordApplic.Documents.Add(refmissing,refmissing,refmissing,refmissing);   
  
            oDoc.Activate();   
        }
publicvoidQuit()   
        {   
            oWordApplic.Application.Quit(
refmissing,refmissing,refmissing);   
        }
///<summary>///附加dot模版文件///</summary>privatevoidLoadDotFile(stringstrDotFile)   
        {
if(!string.IsNullOrEmpty(strDotFile))   
            {   
                Microsoft.Office.Interop.Word.Document wDot
=null;if(oWordApplic!=null)   
                {   
                    oDoc
=oWordApplic.ActiveDocument;   
  
                    oWordApplic.Selection.WholeStory();
//string strContent = oWordApplic.Selection.Text;oWordApplic.Selection.Copy();   
                    wDot
=CreateWordDocument(strDotFile,true);objectbkmC="Content";if(oWordApplic.ActiveDocument.Bookmarks.Exists("Content")==true)   
                    {   
                        oWordApplic.ActiveDocument.Bookmarks.get_Item   
                        (
refbkmC).Select();   
                    }
//对标签"Content"进行填充//直接写入内容不能识别表格什么的//oWordApplic.Selection.TypeText(strContent);oWordApplic.Selection.Paste();   
                    oWordApplic.Selection.WholeStory();   
                    oWordApplic.Selection.Copy();   
                    wDot.Close(
refmissing,refmissing,refmissing);   
  
                    oDoc.Activate();   
                    oWordApplic.Selection.Paste();   
  
                }   
            }   
        }
//////打开Word文档,并且返回对象oDoc///完整Word文件路径+名称///返回的Word.Document oDoc对象publicMicrosoft.Office.Interop.Word.Document CreateWordDocument(stringFileName,boolHideWin)   
        {
if(FileName=="")returnnull;   
  
            oWordApplic.Visible
=HideWin;   
            oWordApplic.Caption
="";   
            oWordApplic.Options.CheckSpellingAsYouType
=false;   
            oWordApplic.Options.CheckGrammarAsYouType
=false;   
  
            Object filename
=FileName;   
            Object ConfirmConversions
=false;   
            Object ReadOnly
=true;   
            Object AddToRecentFiles
=false;   
  
            Object PasswordDocument
=System.Type.Missing;   
            Object PasswordTemplate
=System.Type.Missing;   
            Object Revert
=System.Type.Missing;   
            Object WritePasswordDocument
=System.Type.Missing;   
            Object WritePasswordTemplate
=System.Type.Missing;   
            Object Format
=System.Type.Missing;   
            Object Encoding
=System.Type.Missing;   
            Object Visible
=System.Type.Missing;   
            Object OpenAndRepair
=System.Type.Missing;   
            Object DocumentDirection
=System.Type.Missing;   
            Object NoEncodingDialog
=System.Type.Missing;   
            Object XMLTransform
=System.Type.Missing;try{   
                Microsoft.Office.Interop.Word.Document wordDoc
=oWordApplic.Documents.Open(reffilename,refConfirmConversions,refReadOnly,refAddToRecentFiles,refPasswordDocument,refPasswordTemplate,refRevert,refWritePasswordDocument,refWritePasswordTemplate,refFormat,refEncoding,refVisible,refOpenAndRepair,refDocumentDirection,refNoEncodingDialog,refXMLTransform);returnwordDoc;   
  
            }
catch(Exception ex)   
            {
thrownewException(ex.Message);   
            }   
        }
publicvoidSaveAs(Microsoft.Office.Interop.Word.Document oDoc,stringstrFileName)   
        {
objectfileName=strFileName;if(File.Exists(strFileName))   
            {
thrownewException("文件已经存在!");
            }
else{   
                oDoc.SaveAs(
reffileName,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing);   
            }   
        }
publicvoidSaveAsHtml(Microsoft.Office.Interop.Word.Document oDoc,stringstrFileName)   
        {
objectfileName=strFileName;//wdFormatWebArchive保存为单个网页文件//wdFormatFilteredHTML保存为过滤掉word标签的htm文件,缺点是有图片的话会产生网页文件夹if(File.Exists(strFileName))   
            {
thrownewException("文件已经存在!");
            }
else{objectFormat=(int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;   
                oDoc.SaveAs(
reffileName,refFormat,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing);   
            }   
        }
publicvoidSave()   
        {   
            oDoc.Save();
        }
publicvoidClose()
        {
            oDoc.Close(
refmissing,refmissing,refmissing);//关闭wordApp组件对象oWordApplic.Quit(refmissing,refmissing,refmissing); 
        }
publicvoidSaveAs(stringstrFileName)   
        {
objectFileName=strFileName;objectFileFormat=Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;objectLockComments=false;objectAddToRecentFiles=true;objectReadOnlyRecommended=false;objectEmbedTrueTypeFonts=false;objectSaveNativePictureFormat=true;objectSaveFormsData=true;objectSaveAsAOCELetter=false;objectEncoding=Microsoft.Office.Core.MsoEncoding.msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese;objectInsertLineBreaks=false;objectAllowSubstitutions=false;objectLineEnding=Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;objectAddBiDiMarks=false;try{
                oDoc.SaveAs(
refFileName,refFileFormat,refLockComments,refmissing,refAddToRecentFiles,refmissing,refReadOnlyRecommended,refEmbedTrueTypeFonts,refSaveNativePictureFormat,refSaveFormsData,refSaveAsAOCELetter,refEncoding,refInsertLineBreaks,refAllowSubstitutions,refLineEnding,refAddBiDiMarks);
            }
catch(Exception ex)
            {
thrownewException(ex.Message);
            }
        }
//Save the document in HTML formatpublicvoidSaveAsHtml(stringstrFileName)   
        {
objectfileName=strFileName;objectFormat=(int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;   
            oDoc.SaveAs(
reffileName,refFormat,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing);   
        }
#endregion#region添加菜单(工具栏)项//添加单独的菜单项publicvoidAddMenu(Microsoft.Office.Core.CommandBarPopup popuBar)   
        {   
            Microsoft.Office.Core.CommandBar menuBar
=null;   
            menuBar
=this.oWordApplic.CommandBars["Menu Bar"];   
            popuBar
=(Microsoft.Office.Core.CommandBarPopup)this.oWordApplic.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlPopup, missing, popuBar.Tag,true);if(popuBar==null)   
            {   
                popuBar
=(Microsoft.Office.Core.CommandBarPopup)menuBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlPopup, missing, missing, missing, missing);   
            }   
        }
//添加单独工具栏publicvoidAddToolItem(stringstrBarName,stringstrBtnName)   
        {   
            Microsoft.Office.Core.CommandBar toolBar
=null;   
            toolBar
=(Microsoft.Office.Core.CommandBar)this.oWordApplic.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, missing, strBarName,true);if(toolBar==null)   
            {   
                toolBar
=(Microsoft.Office.Core.CommandBar)this.oWordApplic.CommandBars.Add(   
                     Microsoft.Office.Core.MsoControlType.msoControlButton,   
                     missing, missing, missing);   
                toolBar.Name
=strBtnName;   
                toolBar.Visible
=true;   
            }   
        }
#endregion#region移动光标位置//Go to a predefined bookmark, if the bookmark doesn't exists the application will raise an errorpublicvoidGotoBookMark(stringstrBookMarkName)   
        {
//VB :  Selection.GoTo What:=wdGoToBookmark, Name:="nome"objectBookmark=(int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;objectNameBookMark=strBookMarkName;   
            oWordApplic.Selection.GoTo(
refBookmark,refmissing,refmissing,refNameBookMark);   
        }
publicvoidGoToTheEnd()   
        {
//VB :  Selection.EndKey Unit:=wdStoryobjectunit;   
            unit
=Microsoft.Office.Interop.Word.WdUnits.wdStory;   
            oWordApplic.Selection.EndKey(
refunit,refmissing);   
        }
publicvoidGoToLineEnd()   
        {
objectunit=Microsoft.Office.Interop.Word.WdUnits.wdLine;objectext=Microsoft.Office.Interop.Word.WdMovementType.wdExtend;   
            oWordApplic.Selection.EndKey(
refunit,refext);   
        }
publicvoidGoToTheBeginning()   
        {
//VB : Selection.HomeKey Unit:=wdStoryobjectunit;   
            unit
=Microsoft.Office.Interop.Word.WdUnits.wdStory;   
            oWordApplic.Selection.HomeKey(
refunit,refmissing);   
        }
publicvoidGoToTheTable(intntable)   
        {
objectwhat;   
            what
=Microsoft.Office.Interop.Word.WdUnits.wdTable;objectwhich;   
            which
=Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;objectcount;   
            count
=1;   
            oWordApplic.Selection.GoTo(
refwhat,refwhich,refcount,refmissing);   
            oWordApplic.Selection.Find.ClearFormatting();   
  
            oWordApplic.Selection.Text
="";   
        }
publicvoidGoToRightCell()   
        {
//Selection.MoveRight Unit:=wdCellobjectdirection;   
            direction
=Microsoft.Office.Interop.Word.WdUnits.wdCell;   
            oWordApplic.Selection.MoveRight(
refdirection,refmissing,refmissing);   
        }
publicvoidGoToLeftCell()   
        {
//Selection.MoveRight Unit:=wdCellobjectdirection;   
            direction
=Microsoft.Office.Interop.Word.WdUnits.wdCell;   
            oWordApplic.Selection.MoveLeft(
refdirection,refmissing,refmissing);   
        }
publicvoidGoToDownCell()   
        {
//Selection.MoveRight Unit:=wdCellobjectdirection;   
            direction
=Microsoft.Office.Interop.Word.WdUnits.wdLine;   
            oWordApplic.Selection.MoveDown(
refdirection,refmissing,refmissing);   
        }
publicvoidGoToUpCell()   
        {
//Selection.MoveRight Unit:=wdCellobjectdirection;   
            direction
=Microsoft.Office.Interop.Word.WdUnits.wdLine;   
            oWordApplic.Selection.MoveUp(
refdirection,refmissing,refmissing);   
        }
#endregion#region插入操作publicvoidInsertText(stringstrText)   
        {   
            oWordApplic.Selection.TypeText(strText);   
        }
publicvoidInsertLineBreak()   
        {   
            oWordApplic.Selection.TypeParagraph();   
        }
///<summary>///插入多个空行///</summary>///<param name="nline"></param>publicvoidInsertLineBreak(intnline)   
        {
for(inti=0; i<nline; i++)   
                oWordApplic.Selection.TypeParagraph();   
        }
publicvoidInsertPagebreak()   
        {
//VB : Selection.InsertBreak Type:=wdPageBreakobjectpBreak=(int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;   
            oWordApplic.Selection.InsertBreak(
refpBreak);   
        }
//插入页码publicvoidInsertPageNumber()   
        {
objectwdFieldPage=Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;objectpreserveFormatting=true;   
            oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range,
refwdFieldPage,refmissing,refpreserveFormatting);   
        }
//插入页码publicvoidInsertPageNumber(stringstrAlign)   
        {
objectwdFieldPage=Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;objectpreserveFormatting=true;   
            oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range,
refwdFieldPage,refmissing,refpreserveFormatting);   
            SetAlignment(strAlign);
        }
publicvoidInsertImage(stringstrPicPath,floatpicWidth,floatpicHeight)   
        {
stringFileName=strPicPath;objectLinkToFile=false;objectSaveWithDocument=true;objectAnchor=oWordApplic.Selection.Range;   
            oWordApplic.ActiveDocument.InlineShapes.AddPicture(FileName,
refLinkToFile,refSaveWithDocument,refAnchor).Select();

oWordApplic.Selection.InlineShapes[1].Width=picWidth;//图片宽度oWordApplic.Selection.InlineShapes[1].Height=picHeight;//图片高度//将图片设置为四面环绕型Microsoft.Office.Interop.Word.Shape s=oWordApplic.Selection.InlineShapes[1].ConvertToShape();   
            s.WrapFormat.Type
=Microsoft.Office.Interop.Word.WdWrapType.wdWrapInline;   
        }
publicvoidInsertLine(floatleft,floattop,floatwidth,floatweight,intr,intg,intb)   
        {
//SetFontColor("red");//SetAlignment("Center");objectAnchor=oWordApplic.Selection.Range;//int pLeft = 0, pTop = 0, pWidth = 0, pHeight = 0;//oWordApplic.ActiveWindow.GetPoint(out pLeft, out pTop, out pWidth, out pHeight,missing);//MessageBox.Show(pLeft + "," + pTop + "," + pWidth + "," + pHeight);objectrep=false;//left += oWordApplic.ActiveDocument.PageSetup.LeftMargin;left=oWordApplic.CentimetersToPoints(left);   
            top
=oWordApplic.CentimetersToPoints(top);   
            width
=oWordApplic.CentimetersToPoints(width);   
            Microsoft.Office.Interop.Word.Shape s
=oWordApplic.ActiveDocument.Shapes.AddLine(0, top, width, top,refAnchor);   
            s.Line.ForeColor.RGB
=RGB(r, g, b);   
            s.Line.Visible
=Microsoft.Office.Core.MsoTriState.msoTrue;   
            s.Line.Style
=Microsoft.Office.Core.MsoLineStyle.msoLineSingle;   
            s.Line.Weight
=weight;   
        }
///<summary>///添加页眉///</summary>///<param name="Content">页眉内容</param>///<param name="Alignment">对齐文式</param>publicvoidInsertHeader(stringContent,stringAlignment)
        {
            oWordApplic.ActiveWindow.View.Type
=Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
            oWordApplic.ActiveWindow.View.SeekView
=Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
            oWordApplic.ActiveWindow.ActivePane.Selection.InsertAfter(Content);
            SetAlignment(Alignment);
//设置右对齐oWordApplic.ActiveWindow.View.SeekView=Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
        }
///<summary>///添加页脚///</summary>///<param name="Content">页脚内容</param>///<param name="Alignment">对齐文式</param>publicvoidInsertFooter(stringContent,stringAlignment)
        {
            oWordApplic.ActiveWindow.View.Type
=Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
            oWordApplic.ActiveWindow.View.SeekView
=Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryFooter;
            oWordApplic.ActiveWindow.ActivePane.Selection.InsertAfter(Content);
            SetAlignment(Alignment);
//设置对齐oWordApplic.ActiveWindow.View.SeekView=Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
        }
///<summary>///插入页码///</summary>///<param name="strformat">样式</param>///<param name="strAlign">格式</param>publicvoidInsertAllPageNumber(stringstrformat,stringstrAlign)
        {
objectIncludeFootnotesAndEndnotes=false;intpageSum=oDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages,refIncludeFootnotesAndEndnotes);
            GoToTheBeginning();
for(inti=0; i<pageSum;i++)
            {
                InsertPageNumber();
                oDoc.Application.Browser.Next();
//下一页}
        }
#endregion#region设置样式///<summary>///Change the paragraph alignement///</summary>///<param name="strType"></param>publicvoidSetAlignment(stringstrType)   
        {
switch(strType.ToLower())   
            {
case"center":   
                    oWordApplic.Selection.ParagraphFormat.Alignment
=Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;break;case"left":   
                    oWordApplic.Selection.ParagraphFormat.Alignment
=Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;break;case"right":   
                    oWordApplic.Selection.ParagraphFormat.Alignment
=Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;break;case"justify":   
                    oWordApplic.Selection.ParagraphFormat.Alignment
=Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;break;   
            }   
  
        }
//if you use thif function to change the font you should call it again with//no parameter in order to set the font without a particular formatpublicvoidSetFont(stringstrType)   
        {
switch(strType)   
            {
case"Bold":   
                    oWordApplic.Selection.Font.Bold
=1;break;case"Italic":   
                    oWordApplic.Selection.Font.Italic
=1;break;case"Underlined":   
                    oWordApplic.Selection.Font.Subscript
=0;break;   
            }   
        }
//disable all the stylepublicvoidSetFont()   
        {   
            oWordApplic.Selection.Font.Bold
=0;   
            oWordApplic.Selection.Font.Italic
=0;   
            oWordApplic.Selection.Font.Subscript
=0;   
  
        }
publicvoidSetFontName(stringstrType)   
        {   
            oWordApplic.Selection.Font.Name
=strType;   
        }
publicvoidSetFontSize(floatnSize)   
        {   
            SetFontSize(nSize,
100);   
        }
publicvoidSetFontSize(floatnSize,intscaling)   
        {
if(nSize>0f)   
                oWordApplic.Selection.Font.Size
=nSize;if(scaling>0)   
                oWordApplic.Selection.Font.Scaling
=scaling;   
        }
publicvoidSetFontColor(stringstrFontColor)   
        {
switch(strFontColor.ToLower())   
            {
case"blue":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorBlue;break;case"gold":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorGold;break;case"gray":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorGray875;break;case"green":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorGreen;break;case"lightblue":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;break;case"orange":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorOrange;break;case"pink":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorPink;break;case"red":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorRed;break;case"yellow":   
                    oWordApplic.Selection.Font.Color
=Microsoft.Office.Interop.Word.WdColor.wdColorYellow;break;   
            }   
        }
publicvoidSetPageNumberAlign(stringstrType,boolbHeader)   
        {
objectalignment;objectbFirstPage=false;objectbF=true;//if (bHeader == true)//WordApplic.Selection.HeaderFooter.PageNumbers.ShowFirstPageNumber = bF;switch(strType)   
            {
case"Center":   
                    alignment
=Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;//WordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref bFirstPage);//Microsoft.Office.Interop.Word.Selection objSelection = WordApplic.pSelection;oWordApplic.Selection.HeaderFooter.PageNumbers[1].Alignment=Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;break;case"Right":   
                    alignment
=Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;   
                    oWordApplic.Selection.HeaderFooter.PageNumbers[
1].Alignment=Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;break;case"Left":   
                    alignment
=Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberLeft;   
                    oWordApplic.Selection.HeaderFooter.PageNumbers.Add(
refalignment,refbFirstPage);break;   
            }   
        }
///<summary>///设置页面为标准A4公文样式///</summary>privatevoidSetA4PageSetup()   
        {   
            oWordApplic.ActiveDocument.PageSetup.TopMargin
=oWordApplic.CentimetersToPoints(3.7f);//oWordApplic.ActiveDocument.PageSetup.BottomMargin = oWordApplic.CentimetersToPoints(1f);oWordApplic.ActiveDocument.PageSetup.LeftMargin=oWordApplic.CentimetersToPoints(2.8f);   
            oWordApplic.ActiveDocument.PageSetup.RightMargin
=oWordApplic.CentimetersToPoints(2.6f);//oWordApplic.ActiveDocument.PageSetup.HeaderDistance = oWordApplic.CentimetersToPoints(2.5f);//oWordApplic.ActiveDocument.PageSetup.FooterDistance = oWordApplic.CentimetersToPoints(1f);oWordApplic.ActiveDocument.PageSetup.PageWidth=oWordApplic.CentimetersToPoints(21f);   
            oWordApplic.ActiveDocument.PageSetup.PageHeight
=oWordApplic.CentimetersToPoints(29.7f);   
        }
#endregion#region替换///<summary>///在word 中查找一个字符串直接替换所需要的文本///</summary>///<param name="strOldText">原文本</param>///<param name="strNewText">新文本</param>///<returns></returns>publicboolReplace(stringstrOldText,stringstrNewText)   
        {
if(oDoc==null)   
                oDoc
=oWordApplic.ActiveDocument;this.oDoc.Content.Find.Text=strOldText;objectFindText, ReplaceWith, Replace;//FindText=strOldText;//要查找的文本ReplaceWith=strNewText;//替换文本Replace=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;/**//*wdReplaceAll - 替换找到的所有项。  
                                                      * wdReplaceNone - 不替换找到的任何项。  
                                                    * wdReplaceOne - 替换找到的第一项。  
                                                    *
*/oDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置if(oDoc.Content.Find.Execute(refFindText,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refReplaceWith,refReplace,refmissing,refmissing,refmissing,refmissing))   
            {
returntrue;   
            }
returnfalse;   
        }
publicboolSearchReplace(stringstrOldText,stringstrNewText)   
        {
objectreplaceAll=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;//首先清除任何现有的格式设置选项,然后设置搜索字符串 strOldText。oWordApplic.Selection.Find.ClearFormatting();   
            oWordApplic.Selection.Find.Text
=strOldText;   
  
            oWordApplic.Selection.Find.Replacement.ClearFormatting();   
            oWordApplic.Selection.Find.Replacement.Text
=strNewText;if(oWordApplic.Selection.Find.Execute(refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refreplaceAll,refmissing,refmissing,refmissing,refmissing))   
            {
returntrue;   
            }
returnfalse;   
        }
#endregion#regionrgb转换函数///<summary>///rgb转换函数///</summary>///<param name="r"></param>///<param name="g"></param>///<param name="b"></param>///<returns></returns>intRGB(intr,intg,intb)   
        {
return((b<<16)|(ushort)(((ushort)g<<8)|r));
        }
#endregion#regionRGBToColor///<summary>///RGBToColor///</summary>///<param name="color">颜色值</param>///<returns>Color</returns>Color RGBToColor(intcolor)   
        {
intr=0xFF&color;intg=0xFF00&color;   
            g
>>=8;intb=0xFF0000&color;   
            b
>>=16;returnColor.FromArgb(r, g, b);
        }
#endregion#region读取相关///<summary>///读取第i段内容///</summary>///<param name="i">段索引</param>///<returns>string</returns>publicstringreadParagraph(inti)
        {
try{stringtemp=oDoc.Paragraphs[i].Range.Text.Trim();returntemp;
            }
catch(Exception e) {thrownewException(e.Message);
            }
        }
///<summary>///获得总段数///</summary>///<returns>int</returns>publicintgetParCount()
        {
returnoDoc.Paragraphs.Count;
        }
#endregion}   
}

  三、TXT文档操作类

  这个就是一个.NET中的文件操作类:

TXT文档操作类

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.IO;usingSystem.Data;namespaceBlogMoveLib
{
publicclassFileHelper : IDisposable
    {
privatebool_alreadyDispose=false;#region构造函数publicFileHelper()
        {
////TODO: 在此处添加构造函数逻辑//}~FileHelper()
        {
            Dispose(); ;
        }
protectedvirtualvoidDispose(boolisDisposing)
        {
if(_alreadyDispose)return;
            _alreadyDispose
=true;
        }
#endregion#regionIDisposable 成员publicvoidDispose()
        {
            Dispose(
true);
            GC.SuppressFinalize(
this);
        }
#endregion#region取得文件后缀名/****************************************
          * 函数名称:GetPostfixStr
          * 功能说明:取得文件后缀名
          * 参     数:filename:文件名称
          * 调用示列:
          *            string filename = "aaa.aspx";        
          *            string s = EC.FileObj.GetPostfixStr(filename);         
         ****************************************
*////<summary>///取后缀名///</summary>///<param name="filename">文件名</param>///<returns>.gif|.html格式</returns>publicstaticstringGetPostfixStr(stringfilename)
        {
intstart=filename.LastIndexOf(".");intlength=filename.Length;stringpostfix=filename.Substring(start, length-start);returnpostfix;
        }
#endregion#region写文件/****************************************
          * 函数名称:WriteFile
          * 功能说明:写文件,会覆盖掉以前的内容
          * 参     数:Path:文件路径,Strings:文本内容
          * 调用示列:
          *            string Path = Server.MapPath("Default2.aspx");       
          *            string Strings = "这是我写的内容啊";
          *            EC.FileObj.WriteFile(Path,Strings);
         ****************************************
*////<summary>///写文件///</summary>///<param name="Path">文件路径</param>///<param name="Strings">文件内容</param>publicstaticvoidWriteFile(stringPath,stringStrings)
        {
if(!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f
=System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2
=newSystem.IO.StreamWriter(Path,false, System.Text.Encoding.GetEncoding("gb2312"));
            f2.Write(Strings);
            f2.Close();
            f2.Dispose();
        }
///<summary>///写文件///</summary>///<param name="Path">文件路径</param>///<param name="Strings">文件内容</param>///<param name="encode">编码格式</param>publicstaticvoidWriteFile(stringPath,stringStrings,Encoding encode)
        {
if(!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f
=System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2
=newSystem.IO.StreamWriter(Path,false,encode);
            f2.Write(Strings);
            f2.Close();
            f2.Dispose();
        }
#endregion#region读文件/****************************************
          * 函数名称:ReadFile
          * 功能说明:读取文本内容
          * 参     数:Path:文件路径
          * 调用示列:
          *            string Path = Server.MapPath("Default2.aspx");       
          *            string s = EC.FileObj.ReadFile(Path);
         ****************************************
*////<summary>///读文件///</summary>///<param name="Path">文件路径</param>///<returns></returns>publicstaticstringReadFile(stringPath)
        {
strings="";if(!System.IO.File.Exists(Path))
                s
="不存在相应的目录";else{
                StreamReader f2
=newStreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
                s
=f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }
returns;
        }
///<summary>///读文件///</summary>///<param name="Path">文件路径</param>///<param name="encode">编码格式</param>///<returns></returns>publicstaticstringReadFile(stringPath,Encoding encode)
        {
strings="";if(!System.IO.File.Exists(Path))
                s
="不存在相应的目录";else{
                StreamReader f2
=newStreamReader(Path, encode);
                s
=f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }
returns;
        }
#endregion#region追加文件/****************************************
          * 函数名称:FileAdd
          * 功能说明:追加文件内容
          * 参     数:Path:文件路径,strings:内容
          * 调用示列:
          *            string Path = Server.MapPath("Default2.aspx");     
          *            string Strings = "新追加内容";
          *            EC.FileObj.FileAdd(Path, Strings);
         ****************************************
*////<summary>///追加文件///</summary>///<param name="Path">文件路径</param>///<param name="strings">内容</param>publicstaticvoidFileAdd(stringPath,stringstrings)
        {
            StreamWriter sw
=File.AppendText(Path);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
        }
#endregion#region拷贝文件/****************************************
          * 函数名称:FileCoppy
          * 功能说明:拷贝文件
          * 参     数:OrignFile:原始文件,NewFile:新文件路径
          * 调用示列:
          *            string orignFile = Server.MapPath("Default2.aspx");     
          *            string NewFile = Server.MapPath("Default3.aspx");
          *            EC.FileObj.FileCoppy(OrignFile, NewFile);
         ****************************************
*////<summary>///拷贝文件///</summary>///<param name="OrignFile">原始文件</param>///<param name="NewFile">新文件路径</param>publicstaticvoidFileCoppy(stringorignFile,stringNewFile)
        {
            File.Copy(orignFile, NewFile,
true);
        }
#endregion#region删除文件/****************************************
          * 函数名称:FileDel
          * 功能说明:删除文件
          * 参     数:Path:文件路径
          * 调用示列:
          *            string Path = Server.MapPath("Default3.aspx");    
          *            EC.FileObj.FileDel(Path);
         ****************************************
*////<summary>///删除文件///</summary>///<param name="Path">路径</param>publicstaticvoidFileDel(stringPath)
        {
            File.Delete(Path);
        }
#endregion#region移动文件/****************************************
          * 函数名称:FileMove
          * 功能说明:移动文件
          * 参     数:OrignFile:原始路径,NewFile:新文件路径
          * 调用示列:
          *             string orignFile = Server.MapPath("../说明.txt");    
          *             string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
          *             EC.FileObj.FileMove(OrignFile, NewFile);
         ****************************************
*////<summary>///移动文件///</summary>///<param name="OrignFile">原始路径</param>///<param name="NewFile">新路径</param>publicstaticvoidFileMove(stringorignFile,stringNewFile)
        {
            File.Move(orignFile, NewFile);
        }
#endregion#region在当前目录下创建目录/****************************************
          * 函数名称:FolderCreate
          * 功能说明:在当前目录下创建目录
          * 参     数:OrignFolder:当前目录,NewFloder:新目录
          * 调用示列:
          *            string orignFolder = Server.MapPath("test/");    
          *            string NewFloder = "new";
          *            EC.FileObj.FolderCreate(OrignFolder, NewFloder);
         ****************************************
*////<summary>///在当前目录下创建目录///</summary>///<param name="OrignFolder">当前目录</param>///<param name="NewFloder">新目录</param>publicstaticvoidFolderCreate(stringorignFolder,stringNewFloder)
        {
            Directory.SetCurrentDirectory(orignFolder);
            Directory.CreateDirectory(NewFloder);
        }
#endregion#region递归删除文件夹目录及文件/****************************************
          * 函数名称:DeleteFolder
          * 功能说明:递归删除文件夹目录及文件
          * 参     数:dir:文件夹路径
          * 调用示列:
          *            string dir = Server.MapPath("test/");  
          *            EC.FileObj.DeleteFolder(dir);       
         ****************************************
*////<summary>///递归删除文件夹目录及文件///</summary>///<param name="dir"></param>///<returns></returns>publicstaticvoidDeleteFolder(stringdir)
        {
if(Directory.Exists(dir))//如果存在这个文件夹删除之{foreach(stringdinDirectory.GetFileSystemEntries(dir))
                {
if(File.Exists(d))
                        File.Delete(d);
//直接删除其中的文件elseDeleteFolder(d);//递归删除子文件夹}
                Directory.Delete(dir);
//删除已空文件夹}

}#endregion#region将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。/****************************************
          * 函数名称:CopyDir
          * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
          * 参     数:srcPath:原始路径,aimPath:目标文件夹
          * 调用示列:
          *            string srcPath = Server.MapPath("test/");  
          *            string aimPath = Server.MapPath("test1/");
          *            EC.FileObj.CopyDir(srcPath,aimPath);   
         ****************************************
*////<summary>///指定文件夹下面的所有内容copy到目标文件夹下面///</summary>///<param name="srcPath">原始路径</param>///<param name="aimPath">目标文件夹</param>publicstaticvoidCopyDir(stringsrcPath,stringaimPath)
        {
try{//检查目标目录是否以目录分割字符结束如果不是则添加之if(aimPath[aimPath.Length-1]!=Path.DirectorySeparatorChar)
                    aimPath
+=Path.DirectorySeparatorChar;//判断目标目录是否存在如果不存在则新建之if(!Directory.Exists(aimPath))
                    Directory.CreateDirectory(aimPath);
//得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法//string[] fileList = Directory.GetFiles(srcPath);string[] fileList=Directory.GetFileSystemEntries(srcPath);//遍历所有的文件和目录foreach(stringfileinfileList)
                {
//先当作目录处理如果存在这个目录就递归Copy该目录下面的文件if(Directory.Exists(file))
                        CopyDir(file, aimPath
+Path.GetFileName(file));//否则直接Copy文件elseFile.Copy(file, aimPath+Path.GetFileName(file),true);
                }

}catch(Exception ee)
            {
thrownewException(ee.ToString());
            }
        }
#endregion}
}

  注:在用以上代码时请注意引用命名空间。

作者:天行健,自强不息

出处:http://www.cnblogs.com/durongjian
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载于:https://www.cnblogs.com/artwl/archive/2011/01/05/1926179.html

博客备份系统之一:PDF,Word,TXT文件操作类相关推荐

  1. 推荐一款自己的软件作品[豆约翰博客备份专家],新浪博客,QQ空间,CSDN,cnblogs博客备份,导出CHM,PDF(转载)...

    推荐一款自己的软件作品[豆约翰博客备份专 豆约翰博客备份专家是完全免费,功能强大的博客备份工具,博客电子书(PDF,CHM和TXT)生成工具,博文离线浏览工具,软件界面美观大方,支持多个主流博客网站( ...

  2. 博客备份工具BlogDown 软件使用感想

    最近在找博客备份相关的工具,看到了一个不错的博客备份工具BlogDown.使用博客备份BlogDown工具是可以制作博客电子书的.他支持导出多种文件格式,包括常用的电子书格式chm,还有word格式d ...

  3. switchyomega规则列表备份_求人不如求己,自己动手写一个CSDN博客备份小工具?...

    前提概要 背景 因为笔者在上个月的时候,突然想扩展一下技术栈,不能仅仅局限于Java,还是得掌握一门工具语言,不然显得太low.所以也就对Python和Golang类的语言有了一些兴趣.也就在上个月简 ...

  4. 如何实现Word、PDF,TXT文件的全文内容检索?

    作者 | HENG 来源 | https://www.cnblogs.com/strongchenyu/p/13777596.html 简单介绍一下需求 能支持文件的上传,下载 要能根据关键字,搜索出 ...

  5. 如何实现Word、PDF、TXT文件的全文内容检索?

    简单介绍一下需求 能支持文件的上传,下载 要能根据关键字,搜索出文件,要求要能搜索到文件里的文字,文件类型要支持word,pdf,txt 文件上传,下载比较简单,要能检索到文件里的文字,并且要尽量精确 ...

  6. asp.net921旅游博客网站系统

    项目编号:asp.net921旅游博客网站系统 运行环境:VS+SQL 开发工具:VS2010及以上版本 数据库:SQL2008及以上版本 使用技术:HTML+JS+HTML 开发语言:C#,框架:a ...

  7. 面试官问:如何用Elasticsearch实现Word、PDF,TXT文件的全文内容检索?

    Elasticsearch简介 开发环境 核心问题 文件上传 关键字查询 编码 导入依赖 文件上传 文件查询 多文件测试 还存在的一些问题 简单介绍一下需求 能支持文件的上传,下载 要能根据关键字,搜 ...

  8. 从word、wps、excel、pdf和txt文件中查找文本的工具

    从word.wps.excel.pdf和txt文件中查找文本的工具. 因工作中要经常从大量word文档中查找固定的文本,所以自己就做了本工具. 可以批量从doc.docx.wps.xls.xlsx.p ...

  9. 博客备份攻略(亲自实验绝对可行)

    一.下载blog_backup,下面是它的介绍: (本文系苏克儿原创http://blog.163.com/sukerl@126/,转载请注明原地址:http://blog.163.com/suker ...

  10. python+shell 备份 CSDN 博客文章,CSDN博客备份工具

    python+shell 备份 CSDN 博客文章,CSDN博客备份工具 在 csdn 写了几年的博客了.多少也积累了两三百篇博文,近日,想把自己的这些文章全部备份下来,于是开始寻找解决方案. 我找到 ...

最新文章

  1. 海量数据处理利器之Hash——在线邮件地址过滤
  2. [公告] TechNet / MSDN 经理人博客上周移机整合暂断
  3. MSCRM2011 Current User has Role 【判定当前用户角色方法】
  4. SQL2K数据库开发十五之表操作查看表中的数据
  5. HoloLens开发手记-全息Hologram
  6. 推荐一款接口文档在线管理系统-MinDoc
  7. 电子称测试软件,GS/AJ系列电子秤测量自动记录系统
  8. .net socket与完成端口、异步发送相关研究
  9. CentOS7 安装Redis 单机版
  10. Hibernate笔记①--myeclipse制动配置hibernate
  11. Android apk签名详解——AS签名、获取签名信息、系统签名、命令行签名
  12. xbox win10测试软件,UWP APP可通过Win10商店直接安装至XboxOne主机
  13. 结构化、半结构化、非结构化的理解
  14. VB中关于Array函数与Split函数
  15. 观远数据带你乘云驾“务”,让决策更智能
  16. nmap下载安装介绍使用
  17. 难以置信,网易首席架构师竟用了 500 页笔记,把网络协议给趣谈了
  18. react antd design columns 配置解析
  19. 4.19内核SLUB内存分配器
  20. 2020-8-31 收藏一个api 日历用

热门文章

  1. 王者荣耀服务器维护什么时间结束,3月26日全服不停机更新公告
  2. 自下而上与自上而下的归并排序
  3. 在linux系统下ping不通windows主机问题
  4. 艾永亮:恒大七五折营销事件背后的逻辑与应用
  5. 图片上传时,显示格式错误怎么办?
  6. ffmpeg音频格式转码(编码器)
  7. Delphi中VCL库的原架构师Chuck Jazdzewski回忆Delphi 1的开发原则
  8. 开头的单词_学Z字母本义和引申义,初高中Z开头的单词几分钟全部轻松记忆!...
  9. Cash-Secured Puts Vs. Covered Calls
  10. .bat 是什么? (批处理脚本)