C# 文件操作 全收录 追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件....

简介: 园友总结的很全,可以当工具书查阅了。 http://www.cnblogs.com/zhuzhiyuan/archive/2011/04/22/2024485.html, http://kb.cnblogs.

园友总结的很全,可以当工具书查阅了。

http://www.cnblogs.com/zhuzhiyuan/archive/2011/04/22/2024485.html,

http://kb.cnblogs.com/a/1521799/

后半部分是另外一位总结的

http://www.cnblogs.com/artwl/archive/2011/01/05/1926179.html

 

本文收集了目前最为常用的C#经典操作文件的方法,具体内容如下:C#追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件、指定文件夹下 面的所有内容copy到目标文件夹下面、指定文件夹下面的所有内容Detele、读取文本文件、获取文件列表、读取日志文件、写入日志文件、创建HTML 文件、CreateDirectory方法的使用。

1.C#追加文件

    StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt");
    sw.WriteLine("追逐理想");
    sw.WriteLine("kzlll");
    sw.WriteLine(".NET笔记");
    sw.Flush();
    sw.Close();

  

2.C#拷贝文件

    string OrignFile,NewFile;
    OrignFile = Server.MapPath(".")+"\\myText.txt";
    NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
    File.Copy(OrignFile,NewFile,true);

  

C#删除文件

    string delFile = Server.MapPath(".")+"\\myTextCopy.txt";
    File.Delete(delFile);

  

3.C#移动文件

    string OrignFile,NewFile;
    OrignFile = Server.MapPath(".")+"\\myText.txt";
    NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
    File.Move(OrignFile,NewFile);

  

4.C#创建目录

     // 创建目录c:\sixAge
    DirectoryInfo d=Directory.CreateDirectory("c:\\sixAge"); 
     // d1指向c:\sixAge\sixAge1
    DirectoryInfo d1=d.CreateSubdirectory("sixAge1"); 
     // d2指向c:\sixAge\sixAge1\sixAge1_1
    DirectoryInfo d2=d1.CreateSubdirectory("sixAge1_1"); 
     // 将当前目录设为c:\sixAge
    Directory.SetCurrentDirectory("c:\\sixAge"); 
     // 创建目录c:\sixAge\sixAge2
    Directory.CreateDirectory("sixAge2"); 
     // 创建目录c:\sixAge\sixAge2\sixAge2_1
    Directory.CreateDirectory("sixAge2\\sixAge2_1"); 

  

5.递归删除文件夹及文件

  public void DeleteFolder(string dir)
  {
    if (Directory.Exists(dir)) //如果存在这个文件夹删除之
    {
      foreach(string d in Directory.GetFileSystemEntries(dir))
      {
        if(File.Exists(d))
          File.Delete(d); //直接删除其中的文件
        else
          DeleteFolder(d); //递归删除子文件夹
      }
      Directory.Delete(dir); //删除已空文件夹
      Response.Write(dir+" 文件夹删除成功");
    }
    else
      Response.Write(dir+" 该文件夹不存在"); //如果文件夹不存在则提示
  }
  protected void Page_Load (Object sender ,EventArgs e)
  {
    string Dir="D:\\gbook\\11";
    DeleteFolder(Dir); //调用函数删除文件夹
  }

 

6.copy文件夹内容

实现一个静态方法将指定文件夹下面的所有内容copy到目标文件夹下面,如果目标文件夹为只读属性就会报错。  

  方法1.

  public static void CopyDir(string srcPath,string aimPath)
  {
    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(string file in fileList)
      {
        // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
        if(Directory.Exists(file))
          CopyDir(file,aimPath+Path.GetFileName(file));
        // 否则直接Copy文件
        else
          File.Copy(file,aimPath+Path.GetFileName(file),true);
      }
    }
    catch (Exception e)
    {
      MessageBox.Show (e.ToString());
    }
  }

  方法2.

  public static void CopyFolder(string strFromPath,string strToPath)
  {
    //如果源文件夹不存在,则创建
    if (!Directory.Exists(strFromPath))
    {
      Directory.CreateDirectory(strFromPath);
    }
    //取得要拷贝的文件夹名
    string strFolderName = strFromPath.Substring(strFromPath.LastIndexOf("\\") + 1,strFromPath.Length - strFromPath.LastIndexOf("\\") - 1);
    //如果目标文件夹中没有源文件夹则在目标文件夹中创建源文件夹
    if (!Directory.Exists(strToPath + "\\" + strFolderName))
    {
      Directory.CreateDirectory(strToPath + "\\" + strFolderName);
    }
    //创建数组保存源文件夹下的文件名
    string[] strFiles = Directory.GetFiles(strFromPath);
    //循环拷贝文件
    for(int i = 0;i < strFiles.Length;i++)
    {
    //取得拷贝的文件名,只取文件名,地址截掉。
    string strFileName = strFiles[i].Substring(strFiles[i].LastIndexOf("\\") + 1,strFiles[i].Length - strFiles[i].LastIndexOf("\\") - 1);
    //开始拷贝文件,true表示覆盖同名文件
    File.Copy(strFiles[i],strToPath + "\\" + strFolderName + "\\" + strFileName,true);
    }

    //创建DirectoryInfo实例
    DirectoryInfo dirInfo = new DirectoryInfo(strFromPath);
    //取得源文件夹下的所有子文件夹名称
    DirectoryInfo[] ZiPath = dirInfo.GetDirectories();
    for (int j = 0;j < ZiPath.Length;j++)
    {
      //获取所有子文件夹名
      string strZiPath = strFromPath + "\\" + ZiPath[j].ToString();
      //把得到的子文件夹当成新的源文件夹,从头开始新一轮的拷贝
      CopyFolder(strZiPath,strToPath + "\\" + strFolderName);
    }
  }

  

7.删除文件夹内容

实现一个静态方法将指定文件夹下面的所有内容Detele,测试的时候要小心操作,删除之后无法恢复。

  public static void DeleteDir(string aimPath)
  {
    try
    {
      // 检查目标目录是否以目录分割字符结束如果不是则添加之
      if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
        aimPath += Path.DirectorySeparatorChar;
      // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
      // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法
      // string[] fileList = Directory.GetFiles(aimPath);
      string[] fileList = Directory.GetFileSystemEntries(aimPath);
      // 遍历所有的文件和目录
      foreach(string file in fileList)
      {
        // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件
        if(Directory.Exists(file))
        {
          DeleteDir(aimPath+Path.GetFileName(file));
        }
        // 否则直接Delete文件
        else
        {
          File.Delete (aimPath+Path.GetFileName(file));
        }
      }
    //删除文件夹
    System.IO .Directory .Delete (aimPath,true);
    }
    catch (Exception e)
    {
      MessageBox.Show (e.ToString());
    }
  }

  

8.读取文本文件

 private void ReadFromTxtFile()
 {
    if(filePath.PostedFile.FileName != "")
    {
      txtFilePath =filePath.PostedFile.FileName;
      fileExtName = txtFilePath.Substring(txtFilePath.LastIndexOf(".")+1,3);
 
      if(fileExtName !="txt" && fileExtName != "TXT")
      {
      Response.Write("请选择文本文件");
      }
      else
      {
      StreamReader fileStream = new StreamReader(txtFilePath,Encoding.Default);
      txtContent.Text = fileStream.ReadToEnd();
      fileStream.Close();
     }
    }
  }

  

9.获取文件列表

看到动态表的影子,这个应该是从项目里面拷贝出来的。

private void GetFileList()
{
  string strCurDir,FileName,FileExt;

  /**////文件大小
  long FileSize;

  /**////最后修改时间;
  DateTime FileModify;

  /**////初始化
  if(!IsPostBack)
  {
    /**////初始化时,默认为当前页面所在的目录
    strCurDir = Server.MapPath(".");
    lblCurDir.Text = strCurDir;
    txtCurDir.Text = strCurDir;
  }
  else
  {
    strCurDir = txtCurDir.Text;
    txtCurDir.Text = strCurDir;
    lblCurDir.Text = strCurDir;
  }
  FileInfo fi;
  DirectoryInfo dir;
  TableCell td;
  TableRow tr;
  tr = new TableRow();

  /**////动态添加单元格内容
  td = new TableCell();
  td.Controls.Add(new LiteralControl("文件名"));
  tr.Cells.Add(td);
  td = new TableCell();
  td.Controls.Add(new LiteralControl("文件类型"));
  tr.Cells.Add(td);
  td = new TableCell();
  td.Controls.Add(new LiteralControl("文件大小"));
  tr.Cells.Add(td);
  td = new TableCell();
  td.Controls.Add(new LiteralControl("最后修改时间"));
  tr.Cells.Add(td);

  tableDirInfo.Rows.Add(tr);

  /**////针对当前目录建立目录引用对象
  DirectoryInfo dirInfo = new DirectoryInfo(txtCurDir.Text);

  /**////循环判断当前目录下的文件和目录
  foreach(FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
  {
    FileName = "";
    FileExt = "";
    FileSize = 0;

    /**////如果是文件
    if(fsi is FileInfo)
    {
      fi = (FileInfo)fsi;

      /**////取得文件名
      FileName = fi.Name;

      /**////取得文件的扩展名
      FileExt = fi.Extension;

      /**////取得文件的大小
      FileSize = fi.Length;

      /**////取得文件的最后修改时间
      FileModify = fi.LastWriteTime;
    }

      /**////否则是目录
    else
    {
      dir = (DirectoryInfo)fsi;

      /**////取得目录名
      FileName = dir.Name;

      /**////取得目录的最后修改时间
      FileModify = dir.LastWriteTime;

      /**////设置文件的扩展名为"文件夹"
      FileExt = "文件夹";
    }

    /**////动态添加表格内容
    tr = new TableRow();
    td = new TableCell();
    td.Controls.Add(new LiteralControl(FileName));
    tr.Cells.Add(td);
    td = new TableCell();
    td.Controls.Add(new LiteralControl(FileExt));
    tr.Cells.Add(td);
    td = new TableCell();
    td.Controls.Add(new LiteralControl(FileSize.ToString()+"字节"));
    tr.Cells.Add(td);
    td = new TableCell();
    td.Controls.Add(new LiteralControl(FileModify.ToString("yyyy-mm-dd hh:mm:ss")));
    tr.Cells.Add(td);
    tableDirInfo.Rows.Add(tr);
  }
}

  

10.读取日志文件

   private void ReadLogFile()
   {
     //从指定的目录以打开或者创建的形式读取日志文件
    FileStream fs = new FileStream(Server.MapPath("upedFile")+"\\logfile.txt", FileMode.OpenOrCreate, FileAccess.Read);

    //定义输出字符串
    StringBuilder output = new StringBuilder();

    //初始化该字符串的长度为0
    output.Length = 0;

    //为上面创建的文件流创建读取数据流
    StreamReader read = new StreamReader(fs);

    //设置当前流的起始位置为文件流的起始点
    read.BaseStream.Seek(0, SeekOrigin.Begin);

    //读取文件
    while (read.Peek() > -1)
    {
      //取文件的一行内容并换行
      output.Append(read.ReadLine() + "\n");
    }

    //关闭释放读数据流
    read.Close();

    //返回读到的日志文件内容
    return output.ToString();
  }

  

11.写入日志文件

  private void WriteLogFile(string input)
  {
    //指定日志文件的目录
    string fname = Server.MapPath("upedFile") + "\\logfile.txt";
    //定义文件信息对象
    FileInfo finfo = new FileInfo(fname);

    //判断文件是否存在以及是否大于2K
    if ( finfo.Exists && finfo.Length > 2048 )
    {
      //删除该文件
      finfo.Delete();
    }
    //创建只写文件流
    using(FileStream fs = finfo.OpenWrite())
    {
      //根据上面创建的文件流创建写数据流
      StreamWriter w = new StreamWriter(fs);

      //设置写数据流的起始位置为文件流的末尾
      w.BaseStream.Seek(0, SeekOrigin.End);

      w.Write("\nLog Entry : ");

      //写入当前系统时间并换行
      w.Write("{0} {1} \r\n",DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());

      //写入日志内容并换行
      w.Write(input + "\n");

      //写入------------------------------------“并换行
      w.Write("------------------------------------\n");

      //清空缓冲区内容,并把缓冲区内容写入基础流
      w.Flush();

      //关闭写数据流
      w.Close();
    }
  }

  

12.C#创建HTML文件

  private void CreateHtmlFile()
  {
    //定义和html标记数目一致的数组
    string[] newContent = new string[5];
    StringBuilder strhtml = new StringBuilder();
    try
    {
      //创建StreamReader对象
      using (StreamReader sr = new StreamReader(Server.MapPath("createHTML") + "\\template.html"))
      {
        String oneline;

        //读取指定的HTML文件模板
        while ((oneline = sr.ReadLine()) != null)
        {
          strhtml.Append(oneline);
        }
          sr.Close();
      }
    }
    catch(Exception err)
    {
      //输出异常信息
      Response.Write(err.ToString());
    }
    //为标记数组赋值
    newContent[0] = txtTitle.Text;//标题
    newContent[1] = "BackColor='#cccfff'";//背景色
    newContent[2] = "#ff0000";//字体颜色
    newContent[3] = "100px";//字体大小
    newContent[4] = txtContent.Text;//主要内容

    //根据上面新的内容生成html文件
    try
    {
      //指定要生成的HTML文件
      string fname = Server.MapPath("createHTML") +"\\" + DateTime.Now.ToString("yyyymmddhhmmss") + ".html";

      //替换html模版文件里的标记为新的内容
      for(int i=0;i < 5;i++)
      {
        strhtml.Replace("$htmlkey["+i+"]",newContent[i]);
      }
      //创建文件信息对象
      FileInfo finfo = new FileInfo(fname);

      //以打开或者写入的形式创建文件流
      using(FileStream fs = finfo.OpenWrite())
      {
        //根据上面创建的文件流创建写数据流
        StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));

      //把新的内容写到创建的HTML页面中
      sw.WriteLine(strhtml);
      sw.Flush();
      sw.Close();
    }

      //设置超级链接的属性
      hyCreateFile.Text = DateTime.Now.ToString("yyyymmddhhmmss")+".html";
      hyCreateFile.NavigateUrl = "createHTML/"+DateTime.Now.ToString("yyyymmddhhmmss")+".html";
    }
    catch(Exception err)
    {
      Response.Write (err.ToString());
    }
  }

  

13.CreateDirectory方法的使用

   using System;
   using System.IO;

   class Test 
   {
     public static void Main()
     {
       // Specify the directory you want to manipulate.
       string path = @"c:\MyDir";

       try
       {
         // Determine whether the directory exists.
         if (Directory.Exists(path))
         {
           Console.WriteLine("That path exists already.");
           return;
         }

         // Try to create the directory.
         DirectoryInfo di = Directory.CreateDirectory(path);
         Console.WriteLine("The directory was created successfully at {0}.",   Directory.GetCreationTime(path));

         // Delete the directory.
         di.Delete();
         Console.WriteLine("The directory was deleted successfully.");
       }
       catch (Exception e)
       {
         Console.WriteLine("The process failed: {0}", e.ToString());
       }
       finally {}
     } 
   }

 

14.PDF文件操作类

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

  1、文档的创建

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

         public  Document();
         public  Document(Rectangle pageSize);
         public  Document(Rectangle pageSize,  float  marginLeft,  float  marginRight,  float  marginTop,  float  marginBottom);

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

 

 

  2、字体的设置

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

  BaseFont:  

复制代码
        public   static  BaseFont CreateFont();
        
public   static  BaseFont CreateFont(PRIndirectReference fontRef);
        
public   static  BaseFont CreateFont( string  name,  string  encoding,  bool  embedded);
        
public   static  BaseFont CreateFont( string  name,  string  encoding,  bool  embedded,  bool  forceRead);
        
public   static  BaseFont CreateFont( string  name,  string  encoding,  bool  embedded,  bool  cached,  byte [] ttfAfm,  byte [] pfb);
        
public   static  BaseFont CreateFont( string  name,  string  encoding,  bool  embedded,  bool  cached,  byte [] ttfAfm,  byte [] pfb,  bool  noThrow);
        
public   static  BaseFont CreateFont( string  name,  string  encoding,  bool  embedded,  bool  cached,  byte [] ttfAfm,  byte [] pfb,  bool  noThrow,  bool  forceRead);
复制代码

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

  Font:

复制代码
         public  Font();
        
public  Font(BaseFont bf);
        
public  Font(Font other);
        
public  Font(Font.FontFamily family);
        
public  Font(BaseFont bf,  float  size);
        
public  Font(Font.FontFamily family,  float  size);
        
public  Font(BaseFont bf,  float  size,  int  style);
        
public  Font(Font.FontFamily family,  float  size,  int  style);
        
public  Font(BaseFont bf,  float  size,  int  style, BaseColor color);
        
public  Font(Font.FontFamily family,  float  size,  int  style, BaseColor color);
复制代码

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

  3、添加段落

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

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

         public   virtual   bool  Add(IElement element);

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

  Paragraph的构造函数是:

复制代码
         public  Paragraph();
        
public  Paragraph(Chunk chunk);
        
public  Paragraph( float  leading);
        
public  Paragraph(Phrase phrase);
        
public  Paragraph( string  str);
        
public  Paragraph( float  leading, Chunk chunk);
        
public  Paragraph( float  leading,  string  str);
        
public  Paragraph( string  str, Font font);
        
public  Paragraph( float  leading,  string  str, Font font);
复制代码

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

复制代码
         protected   int  alignment;
        
protected   float  indentationLeft;
        
protected   float  indentationRight;
        
protected   bool  keeptogether;
        
protected   float  multipliedLeading;
        
protected   float  spacingAfter;
        
protected   float  spacingBefore;
复制代码

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

  4、内部链接和外部链接

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

复制代码
             // 外部链接示例
            Anchor anchor  =   new  Anchor( " 博客园 " , font);
            anchor.Reference 
=   " http://www.cnblogs.com " ;
            anchor.Name 
=   " 博客园 " ;

            
// 内部链接示例
            Anchor anc1  =   new  Anchor( " This is an internal link test " );
            anc1.Name 
=   " test " ;
            Anchor anc2 
=   new  Anchor( " Click here to jump to the internal link test " );
            anc2.Reference 
=   " #test "
复制代码

  5、插入图片

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

         public  Image(Image image);
        
public  Image(Uri url);

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

         public   void  ScaleAbsolute( float  newWidth,  float  newHeight);

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

复制代码
         ///   <summary>
        
///  添加图片
        
///   </summary>
        
///   <param name="path"> 图片路径 </param>
        
///   <param name="Alignment"> 对齐方式(1为居中,0为居左,2为居右) </param>
        
///   <param name="newWidth"> 图片宽(0为默认值,如果宽度大于页宽将按比率缩放) </param>
        
///   <param name="newHeight"> 图片高 </param>
         public   void  AddImage( string  path,  int  Alignment,  float  newWidth,  float  newHeight)
        {
            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操作类
复制代码
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  iTextSharp.text;
using  iTextSharp.text.pdf;
using  System.IO;

namespace  BlogBakLib
{
    
///   <summary>
    
///  PDF文档操作类
    
///  作者:天行健,自强不息( http://www.cnblogs.com/durongjian
    
///  创建日期:2011年1月5日
    
///   </summary>
     public   class  PDFOperation
    {
        
// 文档对象
         private  Document document;
        
// 文档大小
         private  Rectangle rect;
        
// 字体
         private  BaseFont basefont;
        
private  Font font;

        
///   <summary>
        
///  构造函数
        
///   </summary>
         public  PDFOperation()
        {
            rect 
=  PageSize.A4;
            document 
=   new  Document(rect);
        }

        
///   <summary>
        
///  构造函数
        
///   </summary>
        
///   <param name="type"> 页面大小(如"A4") </param>
         public  PDFOperation( string  type)
        {
            SetPageSize(type);
            document 
=   new  Document(rect);
        }

        
///   <summary>
        
///  构造函数
        
///   </summary>
        
///   <param name="type"> 页面大小(如"A4") </param>
        
///   <param name="marginLeft"> 内容距左边框距离 </param>
        
///   <param name="marginRight"> 内容距右边框距离 </param>
        
///   <param name="marginTop"> 内容距上边框距离 </param>
        
///   <param name="marginBottom"> 内容距下边框距离 </param>
         public  PDFOperation( string  type, float  marginLeft,  float  marginRight,  float  marginTop,  float  marginBottom)
        {
            SetPageSize(type);
            document 
=   new  Document(rect,marginLeft,marginRight,marginTop,marginBottom);
        }

        
///   <summary>
        
///  构造函数
        
///   </summary>
        
///   <param name="type"> 页面大小(如"A4") </param>
         public  PDFOperation( string  type)
        {
            SetPageSize(type);
            document 
=   new  Document(rect);
        }

        
///   <summary>
        
///  设置页面大小
        
///   </summary>
        
///   <param name="type"> 页面大小(如"A4") </param>
         public   void  SetPageSize( string  type)
        {
            
switch  (type.Trim())
            {
                
case   " A4 " :
                    rect 
=  PageSize.A4;
                    
break ;
                
case   " A8 " :
                    rect 
=  PageSize.A8;
                    
break ;
            }
        }

        
///   <summary>
        
///  设置字体
        
///   </summary>
         public   void  SetBaseFont( string  path)
        {
            basefont 
=  BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }

        
///   <summary>
        
///  设置字体
        
///   </summary>
        
///   <param name="size"> 字体大小 </param>
         public   void  SetFont( float  size)
        {
            font 
=   new  Font(basefont, size);
        }

        
///   <summary>
        
///  实例化文档
        
///   </summary>
        
///   <param name="os"> 文档相关信息(如路径,打开方式等) </param>
         public   void  GetInstance(Stream os)
        {
            PdfWriter.GetInstance(document, os);
        }

        
///   <summary>
        
///  打开文档对象
        
///   </summary>
        
///   <param name="os"> 文档相关信息(如路径,打开方式等) </param>
         public   void  Open(Stream os)
        {
            GetInstance(os);
            document.Open();
        }

        
///   <summary>
        
///  关闭打开的文档
        
///   </summary>
         public   void  Close()
        {
            document.Close();
        }

        
///   <summary>
        
///  添加段落
        
///   </summary>
        
///   <param name="content"> 内容 </param>
        
///   <param name="fontsize"> 字体大小 </param>
         public   void  AddParagraph( string  content,  float  fontsize)
        {
            SetFont(fontsize);
            Paragraph pra 
=   new  Paragraph(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>
         public   void  AddParagraph( string  content,  float  fontsize,  int  Alignment,  float  SpacingAfter,  float  SpacingBefore,  float  MultipliedLeading)
        {
            SetFont(fontsize);
            Paragraph pra 
=   new  Paragraph(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>
         public   void  AddAnchorReference( string  Content,  float  FontSize,  string  Reference)
        {
            SetFont(FontSize);
            Anchor auc 
=   new  Anchor(Content, font);
            auc.Reference 
=  Reference;
            document.Add(auc);
        }

        
///   <summary>
        
///  添加链接点
        
///   </summary>
        
///   <param name="Content"> 链接文字 </param>
        
///   <param name="FontSize"> 字体大小 </param>
        
///   <param name="Name"> 链接点名 </param>
         public   void  AddAnchorName( string  Content,  float  FontSize,  string  Name)
        {
            SetFont(FontSize);
            Anchor auc 
=   new  Anchor(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>
         public   void  AddImage( string  path,  int  Alignment,  float  newWidth,  float  newHeight)
        {
            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操作类就写到这儿吧!因为本人编程是自学的,在编码规范方面可能做的不好,大家对这个类中的代码有什么改进意见请在评论中指出来哦!

 

15.WORD文档操作类

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

WORD操作类
复制代码
using  System;   
using  System.Collections.Generic;   
using  System.Text;   
using  System.Drawing; 
using  System.IO;

namespace  BlogMoveLib   
{
    
public   class  WordOperation   
    {
        
private  Microsoft.Office.Interop.Word.ApplicationClass oWordApplic; 
        
private  Microsoft.Office.Interop.Word.Document oDoc;
        
object  missing  =  System.Reflection.Missing.Value;   
  
        
public  Microsoft.Office.Interop.Word.ApplicationClass WordApplication   
        {   
            
get  {  return  oWordApplic; }   
        }   
  
        
public  WordOperation()   
        {     
            oWordApplic 
=   new  Microsoft.Office.Interop.Word.ApplicationClass();   
        }

        
public  WordOperation(Microsoft.Office.Interop.Word.ApplicationClass wordapp)   
        {   
            oWordApplic 
=  wordapp;   
        }  
 
        
#region  文件操作   
  
        
//  Open a file (the file must exists) and activate it   
         public   void  Open( string  strFileName)   
        {   
            
object  fileName  =  strFileName;
            
object  readOnly  =   false ;
            
object  isVisible  =   true ;   
  
            oDoc 
=  oWordApplic.Documents.Open( ref  fileName,  ref  missing,  ref  readOnly,   
                
ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,   
                
ref  missing,  ref  missing,  ref  isVisible,  ref  missing,  ref  missing,  ref  missing,  ref  missing);   
  
            oDoc.Activate();   
        }   
  
        
//  Open a new document   
         public   void  Open()   
        {   
            oDoc 
=  oWordApplic.Documents.Add( ref  missing,  ref  missing,  ref  missing,  ref  missing);   
  
            oDoc.Activate();   
        }   
  
        
public   void  Quit()   
        {   
            oWordApplic.Application.Quit(
ref  missing,  ref  missing,  ref  missing);   
        }   
  
        
///   <summary>    
        
///  附加dot模版文件   
        
///   </summary>    
         private   void  LoadDotFile( string  strDotFile)   
        {   
            
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 );   
  
                    
object  bkmC  =   " Content " ;   
  
                    
if  (oWordApplic.ActiveDocument.Bookmarks.Exists( " Content " ==   true )   
                    {   
                        oWordApplic.ActiveDocument.Bookmarks.get_Item   
                        (
ref  bkmC).Select();   
                    }   
  
                    
// 对标签"Content"进行填充   
                    
// 直接写入内容不能识别表格什么的   
                    
// oWordApplic.Selection.TypeText(strContent);   
                    oWordApplic.Selection.Paste();   
                    oWordApplic.Selection.WholeStory();   
                    oWordApplic.Selection.Copy();   
                    wDot.Close(
ref  missing,  ref  missing,  ref  missing);   
  
                    oDoc.Activate();   
                    oWordApplic.Selection.Paste();   
  
                }   
            }   
        }   
  
        
///      
        
///  打开Word文档,并且返回对象oDoc   
        
///  完整Word文件路径+名称     
        
///  返回的Word.Document oDoc对象    
         public  Microsoft.Office.Interop.Word.Document CreateWordDocument( string  FileName,  bool  HideWin)   
        {   
            
if  (FileName  ==   "" return   null ;   
  
            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( ref  filename,  ref  ConfirmConversions,   
                
ref  ReadOnly,  ref  AddToRecentFiles,  ref  PasswordDocument,  ref  PasswordTemplate,   
                
ref  Revert,  ref  WritePasswordDocument,  ref  WritePasswordTemplate,  ref  Format,   
                
ref  Encoding,  ref  Visible,  ref  OpenAndRepair,  ref  DocumentDirection,   
                
ref  NoEncodingDialog,  ref  XMLTransform);   
                
return  wordDoc;   
  
            }   
            
catch  (Exception ex)   
            {
                
throw   new  Exception(ex.Message);   
            }   
        }   
  
        
public   void  SaveAs(Microsoft.Office.Interop.Word.Document oDoc,  string  strFileName)   
        {   
            
object  fileName  =  strFileName;   
            
if  (File.Exists(strFileName))   
            {
                
throw   new  Exception( " 文件已经存在! " );
            }   
            
else   
            {   
                oDoc.SaveAs(
ref  fileName,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,   
                        
ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing);   
            }   
        }   
  
        
public   void  SaveAsHtml(Microsoft.Office.Interop.Word.Document oDoc,  string  strFileName)   
        {   
            
object  fileName  =  strFileName;   
  
            
// wdFormatWebArchive保存为单个网页文件   
            
// wdFormatFilteredHTML保存为过滤掉word标签的htm文件,缺点是有图片的话会产生网页文件夹   
             if  (File.Exists(strFileName))   
            {
                
throw   new  Exception( " 文件已经存在! " );
            }   
            
else   
            {   
                
object  Format  =  ( int )Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;   
                oDoc.SaveAs(
ref  fileName,  ref  Format,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,   
                    
ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing);   
            }   
        }   
  
        
public   void  Save()   
        {   
            oDoc.Save();
        }

        
public   void  Close()
        {
            oDoc.Close(
ref  missing,  ref  missing,  ref  missing);
            
// 关闭wordApp组件对象 
            oWordApplic.Quit( ref  missing,  ref  missing,  ref  missing); 
        }
  
        
public   void  SaveAs( string  strFileName)   
        {   
            
object  FileName  = strFileName;
            
object  FileFormat  =  Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
            
object  LockComments  =   false ;
            
object  AddToRecentFiles  =   true ;
            
object  ReadOnlyRecommended  =   false ;
            
object  EmbedTrueTypeFonts  =   false ;
            
object  SaveNativePictureFormat  =   true ;
            
object  SaveFormsData  =   true ;
            
object  SaveAsAOCELetter  =   false ;
            
object  Encoding  =  Microsoft.Office.Core.MsoEncoding.msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese;
            
object  InsertLineBreaks  =   false ;
            
object  AllowSubstitutions  =   false ;
            
object  LineEnding  =  Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;
            
object  AddBiDiMarks  =   false ;

            
try
            {
                oDoc.SaveAs(
ref  FileName,  ref  FileFormat,  ref  LockComments,
                    
ref  missing,  ref  AddToRecentFiles,  ref  missing,
                    
ref  ReadOnlyRecommended,  ref  EmbedTrueTypeFonts,
                    
ref  SaveNativePictureFormat,  ref  SaveFormsData,
                    
ref  SaveAsAOCELetter,  ref  Encoding,  ref  InsertLineBreaks,
                    
ref  AllowSubstitutions,  ref  LineEnding,  ref  AddBiDiMarks);
            }
            
catch  (Exception ex)
            {
                
throw   new  Exception(ex.Message);
            }
        }   
  
        
//  Save the document in HTML format   
         public   void  SaveAsHtml( string  strFileName)   
        {   
            
object  fileName  =  strFileName;   
            
object  Format  =  ( int )Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;   
            oDoc.SaveAs(
ref  fileName,  ref  Format,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,   
                
ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing);   
        }  
 
        
#endregion   
 
        
#region  添加菜单(工具栏)项   
  
        
// 添加单独的菜单项   
         public   void  AddMenu(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);   
            }   
        }   
  
        
// 添加单独工具栏   
         public   void  AddToolItem( string  strBarName, string  strBtnName)   
        {   
            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 error   
         public   void  GotoBookMark( string  strBookMarkName)   
        {   
            
//  VB :  Selection.GoTo What:=wdGoToBookmark, Name:="nome"   
             object  Bookmark  =  ( int )Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;   
            
object  NameBookMark  =  strBookMarkName;   
            oWordApplic.Selection.GoTo(
ref  Bookmark,  ref  missing,  ref  missing,  ref  NameBookMark);   
        }   
  
        
public   void  GoToTheEnd()   
        {   
            
//  VB :  Selection.EndKey Unit:=wdStory   
             object  unit;   
            unit 
=  Microsoft.Office.Interop.Word.WdUnits.wdStory;   
            oWordApplic.Selection.EndKey(
ref  unit,  ref  missing);   
        }   
  
        
public   void  GoToLineEnd()   
        {
            
object  unit  =  Microsoft.Office.Interop.Word.WdUnits.wdLine;   
            
object  ext  =  Microsoft.Office.Interop.Word.WdMovementType.wdExtend;   
            oWordApplic.Selection.EndKey(
ref  unit,  ref  ext);   
        }   
  
        
public   void  GoToTheBeginning()   
        {   
            
//  VB : Selection.HomeKey Unit:=wdStory   
             object  unit;   
            unit 
=  Microsoft.Office.Interop.Word.WdUnits.wdStory;   
            oWordApplic.Selection.HomeKey(
ref  unit,  ref  missing);   
        }   
  
        
public   void  GoToTheTable( int  ntable)   
        {
            
object  what;   
            what 
=  Microsoft.Office.Interop.Word.WdUnits.wdTable;   
            
object  which;   
            which 
=  Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;   
            
object  count;   
            count 
=   1 ;   
            oWordApplic.Selection.GoTo(
ref  what,  ref  which,  ref  count,  ref  missing);   
            oWordApplic.Selection.Find.ClearFormatting();   
  
            oWordApplic.Selection.Text 
=   "" ;   
        }   
  
        
public   void  GoToRightCell()   
        {   
            
//  Selection.MoveRight Unit:=wdCell   
             object  direction;   
            direction 
=  Microsoft.Office.Interop.Word.WdUnits.wdCell;   
            oWordApplic.Selection.MoveRight(
ref  direction,  ref  missing,  ref  missing);   
        }   
  
        
public   void  GoToLeftCell()   
        {   
            
//  Selection.MoveRight Unit:=wdCell   
             object  direction;   
            direction 
=  Microsoft.Office.Interop.Word.WdUnits.wdCell;   
            oWordApplic.Selection.MoveLeft(
ref  direction,  ref  missing,  ref  missing);   
        }   
  
        
public   void  GoToDownCell()   
        {   
            
//  Selection.MoveRight Unit:=wdCell   
             object  direction;   
            direction 
=  Microsoft.Office.Interop.Word.WdUnits.wdLine;   
            oWordApplic.Selection.MoveDown(
ref  direction,  ref  missing,  ref  missing);   
        }   
  
        
public   void  GoToUpCell()   
        {   
            
//  Selection.MoveRight Unit:=wdCell   
             object  direction;   
            direction 
=  Microsoft.Office.Interop.Word.WdUnits.wdLine;   
            oWordApplic.Selection.MoveUp(
ref  direction,  ref  missing,  ref  missing);   
        }  
 
        
#endregion   
 
        
#region  插入操作   
  
        
public   void  InsertText( string  strText)   
        {   
            oWordApplic.Selection.TypeText(strText);   
        }   
  
        
public   void  InsertLineBreak()   
        {   
            oWordApplic.Selection.TypeParagraph();   
        }   
  
        
///   <summary>    
        
///  插入多个空行   
        
///   </summary>    
        
///   <param name="nline"></param>    
         public   void  InsertLineBreak( int  nline)   
        {   
            
for  ( int  i  =   0 ; i  <  nline; i ++ )   
                oWordApplic.Selection.TypeParagraph();   
        }   
  
        
public   void  InsertPagebreak()   
        {   
            
//  VB : Selection.InsertBreak Type:=wdPageBreak   
             object  pBreak  =  ( int )Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;   
            oWordApplic.Selection.InsertBreak(
ref  pBreak);   
        }   
  
        
//  插入页码   
         public   void  InsertPageNumber()   
        {   
            
object  wdFieldPage  =  Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;   
            
object  preserveFormatting  =   true ;   
            oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range, 
ref  wdFieldPage,  ref  missing,  ref  preserveFormatting);   
        }
  
        
//  插入页码   
         public   void  InsertPageNumber( string  strAlign)   
        {   
            
object  wdFieldPage  =  Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;   
            
object  preserveFormatting  =   true ;   
            oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range, 
ref  wdFieldPage,  ref  missing,  ref  preserveFormatting);   
            SetAlignment(strAlign);
        }   
  
        
public   void  InsertImage( string  strPicPath,  float  picWidth,  float  picHeight)   
        {   
            
string  FileName  =  strPicPath;   
            
object  LinkToFile  =   false ;   
            
object  SaveWithDocument  =   true ;   
            
object  Anchor  =  oWordApplic.Selection.Range;   
            oWordApplic.ActiveDocument.InlineShapes.AddPicture(FileName, 
ref  LinkToFile,  ref  SaveWithDocument,  ref  Anchor).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;   
        }   
  
        
public   void  InsertLine( float  left,  float  top,  float  width,  float  weight,  int  r,  int  g,  int  b)   
        {   
            
// SetFontColor("red");   
            
// SetAlignment("Center");   
             object  Anchor  =  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);   
             object  rep  =   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,  ref  Anchor);   
            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>
         public   void  InsertHeader( string  Content,  string  Alignment)
        {
            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>
         public   void  InsertFooter( string  Content,  string  Alignment)
        {
            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>
         public   void  InsertAllPageNumber( string  strformat, string  strAlign)
        {
            
object  IncludeFootnotesAndEndnotes  =   false ;
            
int  pageSum  = oDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages,  ref  IncludeFootnotesAndEndnotes);
            GoToTheBeginning();
            
for  ( int  i  =   0 ; i  <  pageSum;i ++  )
            {
                InsertPageNumber();
                oDoc.Application.Browser.Next();
// 下一页
            }
        }
 
        
#endregion   
 
        
#region  设置样式   
  
        
///   <summary>    
        
///  Change the paragraph alignement   
        
///   </summary>    
        
///   <param name="strType"></param>    
         public   void  SetAlignment( string  strType)   
        {   
            
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 format   
         public   void  SetFont( string  strType)   
        {   
            
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 style    
         public   void  SetFont()   
        {   
            oWordApplic.Selection.Font.Bold 
=   0 ;   
            oWordApplic.Selection.Font.Italic 
=   0 ;   
            oWordApplic.Selection.Font.Subscript 
=   0 ;   
  
        }   
  
        
public   void  SetFontName( string  strType)   
        {   
            oWordApplic.Selection.Font.Name 
=  strType;   
        }   
  
        
public   void  SetFontSize( float  nSize)   
        {   
            SetFontSize(nSize, 
100 );   
        }   
  
        
public   void  SetFontSize( float  nSize,  int  scaling)   
        {   
            
if  (nSize  >  0f)   
                oWordApplic.Selection.Font.Size 
=  nSize;   
            
if  (scaling  >   0 )   
                oWordApplic.Selection.Font.Scaling 
=  scaling;   
        }   
  
        
public   void  SetFontColor( string  strFontColor)   
        {   
            
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 ;   
            }   
        }   
  
        
public   void  SetPageNumberAlign( string  strType,  bool  bHeader)   
        {   
            
object  alignment;   
            
object  bFirstPage  =   false ;   
            
object  bF  =   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(
ref  alignment,  ref  bFirstPage);   
                    
break ;   
            }   
        }   
  
        
///   <summary>    
        
///  设置页面为标准A4公文样式   
        
///   </summary>    
         private   void  SetA4PageSetup()   
        {   
            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>    
         public   bool  Replace( string  strOldText,  string  strNewText)   
        {   
            
if  (oDoc  ==   null )   
                oDoc 
=  oWordApplic.ActiveDocument;   
            
this .oDoc.Content.Find.Text  =  strOldText;   
            
object  FindText, 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(   
                
ref  FindText,  ref  missing,   
                
ref  missing,  ref  missing,   
                
ref  missing,  ref  missing,   
                
ref  missing,  ref  missing,  ref  missing,   
                
ref  ReplaceWith,  ref  Replace,   
                
ref  missing,  ref  missing,   
                
ref  missing,  ref  missing))   
            {   
                
return   true ;   
            }   
            
return   false ;   
        }   
  
        
public   bool  SearchReplace( string  strOldText,  string  strNewText)   
        {   
            
object  replaceAll  =  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(   
                
ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,   
                
ref  missing,  ref  missing,  ref  missing,  ref  missing,  ref  missing,   
                
ref  replaceAll,  ref  missing,  ref  missing,  ref  missing,  ref  missing))   
            {   
                
return   true ;   
            }   
            
return   false ;   
        }  
 
        
#endregion  
  
        
#region  rgb转换函数
        
///   <summary>    
        
///  rgb转换函数   
        
///   </summary>    
        
///   <param name="r"></param>    
        
///   <param name="g"></param>    
        
///   <param name="b"></param>    
        
///   <returns></returns>    
         int  RGB( int  r,  int  g,  int  b)   
        {   
            
return  ((b  <<   16 |  ( ushort )((( ushort )g  <<   8 |  r));
        }
        
#endregion

        
#region  RGBToColor
        
///   <summary>
        
///  RGBToColor
        
///   </summary>
        
///   <param name="color"> 颜色值 </param>
        
///   <returns> Color </returns>
        Color RGBToColor( int  color)   
        {   
            
int  r  =   0xFF   &  color;   
            
int  g  =   0xFF00   &  color;   
            g 
>>=   8 ;   
            
int  b  =   0xFF0000   &  color;   
            b 
>>=   16 ;   
            
return  Color.FromArgb(r, g, b);
        }
        
#endregion

        
#region  读取相关

        
///   <summary>
        
///  读取第i段内容
        
///   </summary>
        
///   <param name="i"> 段索引 </param>
        
///   <returns> string </returns>
         public   string  readParagraph( int  i)
        {
            
try
            {
                
string  temp  =  oDoc.Paragraphs[i].Range.Text.Trim();
                
return  temp;
            }
            
catch  (Exception e) {
                
throw   new  Exception(e.Message);
            }
        }

        
///   <summary>
        
///  获得总段数
        
///   </summary>
        
///   <returns> int </returns>
         public   int  getParCount()
        {
            
return  oDoc.Paragraphs.Count;
        }
        
#endregion

    }   
}
复制代码

 

16.TXT文档操作类

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

TXT文档操作类
复制代码
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.IO;
using  System.Data;

namespace  BlogMoveLib
{
    
public   class  FileHelper : IDisposable
    {
        
private   bool  _alreadyDispose  =   false ;

        
#region  构造函数
        
public  FileHelper()
        {
            
//
            
//  TODO: 在此处添加构造函数逻辑
            
//
        }
        
~ FileHelper()
        {
            Dispose(); ;
        }

        
protected   virtual   void  Dispose( bool  isDisposing)
        {
            
if  (_alreadyDispose)  return ;
            _alreadyDispose 
=   true ;
        }
        
#endregion

        
#region  IDisposable 成员

        
public   void  Dispose()
        {
            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>
         public   static   string  GetPostfixStr( string  filename)
        {
            
int  start  =  filename.LastIndexOf( " . " );
            
int  length  =  filename.Length;
            
string  postfix  =  filename.Substring(start, length  -  start);
            
return  postfix;
        }
        
#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>
         public   static   void  WriteFile( string  Path,  string  Strings)
        {
            
if  ( ! System.IO.File.Exists(Path))
            {
                System.IO.FileStream f 
=  System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 
=   new  System.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>
         public   static   void  WriteFile( string  Path,  string  Strings,Encoding encode)
        {
            
if  ( ! System.IO.File.Exists(Path))
            {
                System.IO.FileStream f 
=  System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 
=   new  System.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>
         public   static   string  ReadFile( string  Path)
        {
            
string  s  =   "" ;
            
if  ( ! System.IO.File.Exists(Path))
                s 
=   " 不存在相应的目录 " ;
            
else
            {
                StreamReader f2 
=   new  StreamReader(Path, System.Text.Encoding.GetEncoding( " gb2312 " ));
                s 
=  f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }

            
return  s;
        }

        
///   <summary>
        
///  读文件
        
///   </summary>
        
///   <param name="Path"> 文件路径 </param>
        
///   <param name="encode"> 编码格式 </param>
        
///   <returns></returns>
         public   static   string  ReadFile( string  Path,Encoding encode)
        {
            
string  s  =   "" ;
            
if  ( ! System.IO.File.Exists(Path))
                s 
=   " 不存在相应的目录 " ;
            
else
            {
                StreamReader f2 
=   new  StreamReader(Path, encode);
                s 
=  f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }

            
return  s;
        }
        
#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>
         public   static   void  FileAdd( string  Path,  string  strings)
        {
            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>
         public   static   void  FileCoppy( string  orignFile,  string  NewFile)
        {
            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>
         public   static   void  FileDel( string  Path)
        {
            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>
         public   static   void  FileMove( string  orignFile,  string  NewFile)
        {
            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>
         public   static   void  FolderCreate( string  orignFolder,  string  NewFloder)
        {
            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>
         public   static   void  DeleteFolder( string  dir)
        {
            
if  (Directory.Exists(dir))  // 如果存在这个文件夹删除之
            {
                
foreach  ( string  d  in  Directory.GetFileSystemEntries(dir))
                {
                    
if  (File.Exists(d))
                        File.Delete(d); 
// 直接删除其中的文件
                     else
                        DeleteFolder(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>
         public   static   void  CopyDir( string  srcPath,  string  aimPath)
        {
            
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  ( string  file  in  fileList)
                {
                    
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

                    
if  (Directory.Exists(file))
                        CopyDir(file, aimPath 
+  Path.GetFileName(file));
                    
// 否则直接Copy文件
                     else
                        File.Copy(file, aimPath 
+  Path.GetFileName(file),  true );
                }

            }
            
catch  (Exception ee)
            {
                
throw   new  Exception(ee.ToString());
            }
        }
        
#endregion
    }
}
复制代码

 

作者:Tyler Ning
出处:http://www.cnblogs.com/tylerdonet/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址williamningdong@gmail.com  联系我,非常感谢。

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
29天前
|
XML C# 数据格式
使用C#操作XML文件
使用C#操作XML文件
11 0
|
1月前
|
C#
C# 文件操作(全部) 追加、拷贝、删除、移动文件、创建目录
C# 文件操作(全部) 追加、拷贝、删除、移动文件、创建目录
21 0
|
3月前
|
C# Python
C# 笔记1 - 操作目录
C# 笔记1 - 操作目录
29 0
|
3月前
|
C#
C#读取html文件
C#读取html文件
28 3
|
25天前
|
安全 数据处理 C#
C# Post数据或文件到指定的服务器进行接收
C# Post数据或文件到指定的服务器进行接收
|
25天前
|
C# 开发工具 数据安全/隐私保护
C#实现基于Word保护性模板文件的修改
C#实现基于Word保护性模板文件的修改
|
2月前
|
C#
C# Winform 选择文件夹和选择文件
C# Winform 选择文件夹和选择文件
43 0
|
1月前
|
C#
24. C# 编程:用户设定敌人初始血值的实现
24. C# 编程:用户设定敌人初始血值的实现
18 0
|
2月前
|
SQL 数据库连接 应用服务中间件
C#WinForm基础编程(三)
C#WinForm基础编程
71 0
|
2月前
C#WinForm基础编程(二)
C#WinForm基础编程
55 0