天天看點

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

園友總結的很全,可以當工具書查閱了。

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(".")+"

";

    NewFile = Server.MapPath(".")+"

\\myTextCopy.txt

    File.Copy(OrignFile,NewFile,true);

C#删除檔案

    string delFile = Server.MapPath(".")+"

    File.Delete(delFile);

3.C#移動檔案

    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)

      // 如果你指向Delete目标檔案下面的檔案而不包含目錄請使用下面的方法

      // string[] fileList = Directory.GetFiles(aimPath);

      string[] fileList = Directory.GetFileSystemEntries(aimPath);

        // 先當作目錄處理如果存在這個目錄就遞歸Delete該目錄下面的檔案

        {

          DeleteDir(aimPath+Path.GetFileName(file));

        }

        // 否則直接Delete檔案

          File.Delete (aimPath+Path.GetFileName(file));

    //删除檔案夾

    System.IO .Directory .Delete (aimPath,true);

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;

  FileInfo fi;

  DirectoryInfo dir;

  TableCell td;

  TableRow tr;

  tr = new TableRow();

  /**////動态添加單元格内容

  td = new TableCell();

  td.Controls.Add(new LiteralControl("檔案名"));

  tr.Cells.Add(td);

  td.Controls.Add(new LiteralControl("檔案類型"));

  td.Controls.Add(new LiteralControl("檔案大小"));

  td.Controls.Add(new LiteralControl("最後修改時間"));

  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.Controls.Add(new LiteralControl(FileExt));

    td.Controls.Add(new LiteralControl(FileSize.ToString()+"位元組"));

    td.Controls.Add(new LiteralControl(FileModify.ToString("yyyy-mm-dd hh:mm:ss")));

    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") + "

";

    //定義檔案資訊對象

    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檔案

      //指定要生成的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";

      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:  

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

        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);

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

  預設的構造函數用的是英文字型,如果想用中文一般用的是第三個構造函數,這三個參數前兩個意思是字型名子或字型資源路徑,第三個參數我也沒弄明

白是什麼意思。如果用字型名子其實用的是這個DLL内置字型,如果用字型資源名子可以用系統字型存放路徑,如“C:\Windows\Fonts

\SIMHEI.TTF”(windows系統),也可以把字型檔案放在應用程式目錄,然後取這個路徑。

  Font:

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

        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);

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

  一般用的是第五個構造函數,也就是從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的構造函數是:

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

        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);

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

  大家可以看到Chunk、Phrase都可以執行個體化Paragraph,不過我用的比較多的是倒數第二個。當然了,Paragraph還有一些屬性可以讓我們給段落設定一些格式,比如對齊方式,段前空行數,段後空行數,行間距等。 這些屬性如下:

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

        protected int alignment;

        protected float indentationLeft;

        protected float indentationRight;

        protected bool keeptogether;

        protected float multipliedLeading;

        protected float spacingAfter;

        protected float spacingBefore;

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

  略作解釋:alignmant為對齊方式(1為居中,0為居左,2為居右),indentationLeft為左縮

進,indentationRight為右縮進,keeptogether保持在一起(常用在對内容絕對定位),multipliedLeading為行

間距,spacingAfter為段前空行數,spacingBefore為段後空行數。

  4、内部連結和外部連結

  連結在iTextSharp中有Anchor對象,它有兩個屬性,name和reference,name自然就是連結的名稱

了,reference就是連結的位址了,如果是外部連結reference直接就是一個網址,如果是内部連結,就跟html中的錨一樣,用'#'加上

name名,示例如下:

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

            //外部連結示例

            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"; 

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

  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);

  看參數就知道是給圖檔重新設定寬度和高度的,我的做法是如果圖檔寬度大于文檔寬度就按比例縮小,否則不處理:

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

        /// <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);

        }

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

  其中的rect是我定義的一個文檔大小屬性。

  好了,下面就貼出我的PDF文檔操作類吧。為了達到封裝的目地(這裡說的封裝意思是調用的類可以不引用iTextSharp這個DLL),我在

傳參過程中做了一點更改。如設定頁面大小時Document的構造函數中提供了用Rectangle對象執行個體化,但因為這個類是iTextSharp中

的,是以我改為傳一個字元串(如"A4"),根據這個字元串執行個體化一個Rectangle對象,再來設定頁面大小,其它地方類似。

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

PDF操作類

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

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;

        /// 構造函數

        public PDFOperation()

            rect = PageSize.A4;

            document = new Document(rect);

        /// <param name="type">頁面大小(如"A4")</param>

        public PDFOperation(string type)

            SetPageSize(type);

        /// <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)

            document = new Document(rect,marginLeft,marginRight,marginTop,marginBottom);

        /// 設定頁面大小

        public void SetPageSize(string type)

            switch (type.Trim())

                case "A4":

                    rect = PageSize.A4;

                    break;

                case "A8":

                    rect = PageSize.A8;

        /// 設定字型

        public void SetBaseFont(string path)

            basefont = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        /// <param name="size">字型大小</param>

        public void SetFont(float size)

            font = new Font(basefont, size);

        /// 執行個體化文檔

        /// <param name="os">文檔相關資訊(如路徑,打開方式等)</param>

        public void GetInstance(Stream os)

            PdfWriter.GetInstance(document, os);

        /// 打開文檔對象

        public void Open(Stream os)

            GetInstance(os);

            document.Open();

        /// 關閉打開的文檔

        public void Close()

            document.Close();

        /// 添加段落

        /// <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);

        /// <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)

            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;

        /// 添加連結

        /// <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);

        /// 添加連結點

        /// <param name="Name">連結點名</param>

        public void AddAnchorName(string Content, float FontSize, string Name)

            auc.Name = Name;

    }

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

  好了,PDF操作類就寫到這兒吧!因為本人程式設計是自學的,在編碼規範方面可能做的不好,大家對這個類中的代碼有什麼改進意見請在評論中指出來哦!

15.WORD文檔操作類

  這個就不說了,直接貼代碼:  

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

WORD操作類

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

using System;   

using System.Collections.Generic;   

using System.Text;   

using System.Drawing; 

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);   

        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();   

                    wDot.Close(ref missing, ref missing, ref missing);   

                    oDoc.Activate();   

                }   

            }   

        ///     

        /// 打開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)   

            //wdFormatWebArchive儲存為單個網頁檔案   

            //wdFormatFilteredHTML儲存為過濾掉word标簽的htm檔案,缺點是有圖檔的話會産生網頁檔案夾   

                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();

            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 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;   

        #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   

            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()   

            oWordApplic.Selection.MoveLeft(ref direction, ref missing, ref missing);   

        public void GoToDownCell()   

            direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;   

            oWordApplic.Selection.MoveDown(ref direction, ref missing, ref missing);   

        public void GoToUpCell()   

            oWordApplic.Selection.MoveUp(ref direction, ref missing, ref missing);   

        #region 插入操作   

        public void InsertText(string strText)   

            oWordApplic.Selection.TypeText(strText);   

        public void InsertLineBreak()   

            oWordApplic.Selection.TypeParagraph();   

        /// 插入多個空行   

        /// <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)   

            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");   

            //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;   

        /// 添加頁眉

        /// <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;

        /// 添加頁腳

        /// <param name="Content">頁腳内容</param>

        public void InsertFooter(string Content, string Alignment)

            oWordApplic.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryFooter;

            SetAlignment(Alignment);// 設定對齊

        /// 插入頁碼

        /// <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();//下一頁

        #region 設定樣式   

        /// Change the paragraph alignement   

        /// <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;   

                case "right":   

                    oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;   

                case "justify":   

                    oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;   

        // 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;   

                case "Italic":   

                    oWordApplic.Selection.Font.Italic = 1;   

                case "Underlined":   

                    oWordApplic.Selection.Font.Subscript = 0;   

        // 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;   

                case "gold":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorGold;   

                case "gray":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorGray875;   

                case "green":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;   

                case "lightblue":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;   

                case "orange":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorOrange;   

                case "pink":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorPink;   

                case "red":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;   

                case "yellow":   

                    oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorYellow;   

        public void SetPageNumberAlign(string strType, bool bHeader)   

            object alignment;   

            object bFirstPage = false;   

            object bF = true;   

            //if (bHeader == true)   

            //WordApplic.Selection.HeaderFooter.PageNumbers.ShowFirstPageNumber = bF;   

                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;   

                case "Right":   

                    alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;   

                    oWordApplic.Selection.HeaderFooter.PageNumbers[1].Alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;   

                case "Left":   

                    alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberLeft;   

                    oWordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment, ref bFirstPage);   

        /// 設定頁面為标準A4公文樣式   

        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);   

        #region 替換   

        ///<summary>   

        /// 在word 中查找一個字元串直接替換所需要的文本   

        /// <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 ReplaceWith, ref Replace,   

                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.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 replaceAll, ref missing, ref missing, ref missing, ref missing))   

        #endregion 

        #region rgb轉換函數

        /// rgb轉換函數   

        /// <param name="r"></param>   

        /// <param name="g"></param>   

        /// <param name="b"></param>   

        int RGB(int r, int g, int b)   

            return ((b << 16) | (ushort)(((ushort)g << 8) | r));

        #endregion

        #region RGBToColor

        /// RGBToColor

        /// <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);

        #region 讀取相關

        /// 讀取第i段内容

        /// <param name="i">段索引</param>

        /// <returns>string</returns>

        public string readParagraph(int i)

                string temp = oDoc.Paragraphs[i].Range.Text.Trim();

                return temp;

            catch (Exception e) {

                throw new Exception(e.Message);

        /// 獲得總段數

        /// <returns>int</returns>

        public int getParCount()

            return oDoc.Paragraphs.Count;

    }   

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

16.TXT文檔操作類

  這個就是一個.NET中的檔案操作類:

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

TXT文檔操作類

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

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;

        #region IDisposable 成員

        public void Dispose()

            Dispose(true);

            GC.SuppressFinalize(this);

        #region 取得檔案字尾名

        /****************************************

          * 函數名稱:GetPostfixStr

          * 功能說明:取得檔案字尾名

          * 參     數:filename:檔案名稱

          * 調用示列:

          *            string filename = "aaa.aspx";        

          *            string s = EC.FileObj.GetPostfixStr(filename);         

         *****************************************/

        /// 取字尾名

        /// <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;

        #region 寫檔案

          * 函數名稱:WriteFile

          * 功能說明:寫檔案,會覆寫掉以前的内容

          * 參     數:Path:檔案路徑,Strings:文本内容

          *            string Path = Server.MapPath("Default2.aspx");       

          *            string Strings = "這是我寫的内容啊";

          *            EC.FileObj.WriteFile(Path,Strings);

        /// 寫檔案

        /// <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();

        /// <param name="encode">編碼格式</param>

        public static void WriteFile(string Path, string Strings,Encoding encode)

            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false,encode);

        #region 讀檔案

          * 函數名稱:ReadFile

          * 功能說明:讀取文本内容

          * 參     數:Path:檔案路徑

          *            string s = EC.FileObj.ReadFile(Path);

        /// 讀檔案

        /// <returns></returns>

        public static string ReadFile(string Path)

            string s = "";

                s = "不存在相應的目錄";

                StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));

                s = f2.ReadToEnd();

                f2.Close();

                f2.Dispose();

            return s;

        public static string ReadFile(string Path,Encoding encode)

                StreamReader f2 = new StreamReader(Path, encode);

        #region 追加檔案

          * 函數名稱:FileAdd

          * 功能說明:追加檔案内容

          * 參     數:Path:檔案路徑,strings:内容

          *            string Path = Server.MapPath("Default2.aspx");     

          *            string Strings = "新追加内容";

          *            EC.FileObj.FileAdd(Path, Strings);

        /// 追加檔案

        /// <param name="strings">内容</param>

        public static void FileAdd(string Path, string strings)

            StreamWriter sw = File.AppendText(Path);

            sw.Write(strings);

            sw.Flush();

            sw.Close();

        #region 拷貝檔案

          * 函數名稱:FileCoppy

          * 功能說明:拷貝檔案

          * 參     數:OrignFile:原始檔案,NewFile:新檔案路徑

          *            string orignFile = Server.MapPath("Default2.aspx");     

          *            string NewFile = Server.MapPath("Default3.aspx");

          *            EC.FileObj.FileCoppy(OrignFile, NewFile);

        /// 拷貝檔案

        /// <param name="OrignFile">原始檔案</param>

        /// <param name="NewFile">新檔案路徑</param>

        public static void FileCoppy(string orignFile, string NewFile)

            File.Copy(orignFile, NewFile, true);

        #region 删除檔案

          * 函數名稱:FileDel

          * 功能說明:删除檔案

          *            string Path = Server.MapPath("Default3.aspx");    

          *            EC.FileObj.FileDel(Path);

        /// 删除檔案

        /// <param name="Path">路徑</param>

        public static void FileDel(string Path)

            File.Delete(Path);

        #region 移動檔案

          * 函數名稱:FileMove

          * 功能說明:移動檔案

          * 參     數:OrignFile:原始路徑,NewFile:新檔案路徑

          *             string orignFile = Server.MapPath("../說明.txt");    

          *             string NewFile = Server.MapPath("http://www.cnblogs.com/說明.txt");

          *             EC.FileObj.FileMove(OrignFile, NewFile);

        /// 移動檔案

        /// <param name="OrignFile">原始路徑</param>

        /// <param name="NewFile">新路徑</param>

        public static void FileMove(string orignFile, string NewFile)

            File.Move(orignFile, NewFile);

        #region 在目前目錄下建立目錄

          * 函數名稱:FolderCreate

          * 功能說明:在目前目錄下建立目錄

          * 參     數:OrignFolder:目前目錄,NewFloder:新目錄

          *            string orignFolder = Server.MapPath("test/");    

          *            string NewFloder = "new";

          *            EC.FileObj.FolderCreate(OrignFolder, NewFloder);

        /// 在目前目錄下建立目錄

        /// <param name="OrignFolder">目前目錄</param>

        /// <param name="NewFloder">新目錄</param>

        public static void FolderCreate(string orignFolder, string NewFloder)

            Directory.SetCurrentDirectory(orignFolder);

            Directory.CreateDirectory(NewFloder);

        #region 遞歸删除檔案夾目錄及檔案

          * 函數名稱:DeleteFolder

          * 功能說明:遞歸删除檔案夾目錄及檔案

          * 參     數:dir:檔案夾路徑

          *            string dir = Server.MapPath("test/");  

          *            EC.FileObj.DeleteFolder(dir);       

        /// 遞歸删除檔案夾目錄及檔案

        /// <param name="dir"></param>

        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); //删除已空檔案夾

        #region 将指定檔案夾下面的所有内容copy到目标檔案夾下面 果目标檔案夾為隻讀屬性就會報錯。

          * 函數名稱:CopyDir

          * 功能說明:将指定檔案夾下面的所有内容copy到目标檔案夾下面 果目标檔案夾為隻讀屬性就會報錯。

          * 參     數:srcPath:原始路徑,aimPath:目标檔案夾

          *            string srcPath = Server.MapPath("test/");  

          *            string aimPath = Server.MapPath("test1/");

          *            EC.FileObj.CopyDir(srcPath,aimPath);   

        /// 指定檔案夾下面的所有内容copy到目标檔案夾下面

        /// <param name="srcPath">原始路徑</param>

        /// <param name="aimPath">目标檔案夾</param>

        public static void CopyDir(string srcPath, string aimPath)

                // 檢查目标目錄是否以目錄分割字元結束如果不是則添加之

                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檔案

                        File.Copy(file, aimPath + Path.GetFileName(file), true);

            catch (Exception ee)

                throw new Exception(ee.ToString());

C# 檔案操作 全收錄 追加、拷貝、删除、移動檔案、建立目錄、遞歸删除檔案夾及檔案....

作者:

Tyler Ning

出處:

http://www.cnblogs.com/tylerdonet/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,如有問題,可以通過以下郵箱位址

[email protected]

 聯系我,非常感謝。