C#檔案操作集錦

來源:互聯網
上載者:User
C#檔案操作:C#追加檔案StreamWriter sw = File.AppendText(  Server.MapPath(".")+"\\myText.txt");   sw.WriteLine("追逐理想");   sw.WriteLine("kzlll");   sw.WriteLine(".NET筆記");   sw.Flush();   sw.Close();   C#檔案操作:C#拷貝檔案string OrignFile,NewFile;   OrignFile = Server.MapPath(  ".")+"\\myText.txt";   NewFile = Server.MapPath(  ".")+"\\myTextCopy.txt";   File.Copy(OrignFile,NewFile,true);   C#檔案操作:C#刪除檔案string delFile = Server.MapPath(  ".")+"\\myTextCopy.txt";   File.Delete(delFile);   C#檔案操作:C#移動檔案string OrignFile,NewFile;   OrignFile = Server.MapPath(  ".")+"\\myText.txt";   NewFile = Server.MapPath(  ".")+"\\myTextCopy.txt";   File.Move(OrignFile,NewFile);   C#檔案操作: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");  遞迴刪除檔案夾及檔案〈%@PageLanguage=C#%〉  〈%@Importnamespace="System.IO"%〉  〈Scriptrunat=server〉  publicvoidDeleteFolder(stringdir)  {  if(Directory.Exists(dir))//如果  存在這個檔案夾刪除之  {  foreach(stringdinDirectory.  GetFileSystemEntries(dir))  {  if(File.Exists(d))  File.Delete(d);//直接刪除其中的檔案  else DeleteFolder(d);//遞迴刪除子檔案夾  }  Directory.Delete(dir);//刪除已空檔案夾  Response.Write(dir+"檔案夾刪除成功");  }  else Response.Write(dir+"該檔案夾不存在");//如果  檔案夾不存在則提示  }  protectedvoidPage_Load(Object  sender,EventArgse)  {  stringDir="D:\\gbook\\11";  DeleteFolder(Dir);//調用函數刪除檔案夾  }    //========================================  //實現一個靜態方法將指定檔案夾下面的  所有內容copy到目標檔案夾下面  //如果目標檔案夾為唯讀屬性就會報錯。  //April18April2005InSTU  //========================================  publicstaticvoidCopyDir(stringsrcPath,  stringaimPath)  {  try  {  //檢查目標目錄是否以目錄分割字  符結束如果不是則添加之  if(aimPath[aimPath.Length-1]!=  Path.DirectorySeparatorChar)  aimPath+=Path.DirectorySeparatorChar;  //判斷目標目錄是否存在如果不存在則建立之  if(!Directory.Exists(aimPath))Directory.  CreateDirectory(aimPath);  //得到來源目錄的檔案清單,  該裡面是包含檔案以及目錄路徑的一個數組  //如果你指向copy目標檔案下面的檔案  而不包含目錄請使用下面的方法  //string[]fileList=  Directory.GetFiles(srcPath);  string[]fileList=  Directory.GetFileSystemEntries(srcPath);  //遍曆所有的檔案和目錄  foreach(stringfileinfileList)  {  //先當作目錄處理如果存在這個  目錄就遞迴Copy該目錄下面的檔案  if(Directory.Exists(file))  CopyDir(file,aimPath+Path.GetFileName(file));  //否則直接Copy檔案  else File.Copy(file,aimPath+Path.GetFileName(  file),true);  }  }  catch(Exceptione)  {  MessageBox.Show(e.ToString());  }  }  //========================================  //實現一個靜態方法將指定文  件夾下面的所有內容Detele  //測試的時候要小心操作,刪除之後無法恢複。  //April18April2005InSTU  //========================================  publicstaticvoidDeleteDir(stringaimPath)  {  try  {  //檢查目標目錄是否以目錄分割字  符結束如果不是則添加之  if(aimPath[aimPath.Length-1]!=  Path.DirectorySeparatorChar)  aimPath+=Path.DirectorySeparatorChar;  //得到來源目錄的檔案清單,  該裡面是包含檔案以及目錄路徑的一個數組  //如果你指向Delete目標檔案下面的  檔案而不包含目錄請使用下面的方法  //string[]fileList=  Directory.GetFiles(aimPath);  string[]fileList=  Directory.GetFileSystemEntries(aimPath);  //遍曆所有的檔案和目錄  foreach(stringfileinfileList)  {  //先當作目錄處理如果存在這個  目錄就遞迴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(Exceptione)  {  MessageBox.Show(e.ToString());  }  }   需要引用命名空間:  usingSystem.IO;   /**////〈summary〉  ///拷貝檔案夾(包括子檔案夾)到指定檔案夾下,  源檔案夾和目標檔案夾均需絕對路徑.  格式:CopyFolder(源檔案夾,目標檔案夾);  ///〈/summary〉  ///〈paramname="strFromPath"〉〈/param〉  ///〈paramname="strToPath"〉〈/param〉   //----------------------------------------  //作者:明天去要飯QQ:305725744  //----------------------------------------  publicstaticvoidCopyFolder(stringstrFromPath,  stringstrToPath)  {  //如果源檔案夾不存在,則建立  if(!Directory.Exists(strFromPath))  {  Directory.CreateDirectory(strFromPath);  }   //取得要拷貝的檔案夾名  stringstrFolderName=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(inti=0;i〈strFiles.Length;i++)  {  //取得拷貝的檔案名稱,只取檔案名稱,地址截掉。  stringstrFileName=strFiles[i].Substring(  strFiles[i].LastIndexOf("\\")+1,  strFiles[i].Length-strFiles[i].  LastIndexOf("\\")-1);  //開始拷貝檔案,true表示覆蓋同名檔案  File.Copy(strFiles[i],strToPath+"\\" +strFolderName+"\\"+strFileName,true);  }   //建立DirectoryInfo執行個體  DirectoryInfodirInfo=newDirectoryInfo(  strFromPath);  //取得源檔案夾下的所有子檔案夾名稱  DirectoryInfo[]ZiPath=dirInfo.GetDirectories();  for(intj=0;j〈ZiPath.Length;j++)  {  //擷取所有子檔案夾名  stringstrZiPath=strFromPath+"\\"+  ZiPath[j].ToString();  //把得到的子檔案夾當成新的源檔案夾,  從頭開始新一輪的拷貝  CopyFolder(strZiPath,strToPath+"\\"+  strFolderName);  }  }  C#檔案操作:讀取文字檔**//// 〈summary〉  // 讀取文字檔  // 〈/summary〉  4private void ReadFromTxtFile()  5{     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();    }    }  }C#檔案操作:擷取檔案清單**//// 〈summary〉  // 擷取檔案清單  // 〈/summary〉  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);     }  } C#檔案操作:讀取記錄檔**//// 〈summary〉  // 讀取記錄檔  // 〈/summary〉  private void ReadLogFile()  {     /**////從指定的目錄以打  開或者建立的形式讀取記錄檔     FileStream fs =   new FileStream(Server.MapPath("upedFile" )+"\\logfile.txt", FileMode.OpenOrCreate,   FileAccess.Read);      /**////定義輸出字串     StringBuilder output =   new StringBuilder();          /**////初始化該字串的長度為    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();  } C#檔案操作:寫入記錄檔**//// 〈summary〉  // 寫入記錄檔  // 〈/summary〉  // 〈param name="input"〉〈/param〉  private void WriteLogFile(string input)  {         /**////指定記錄檔的目錄     string fname = Server.MapPath(  "upedFile") + "\\logfile.txt";     /**////定義檔案資訊對象     FileInfo finfo = new FileInfo(fname);      /**////判斷檔案是否存在以及是否大於2K     if ( finfo.Exists && finfo.Length 〉   )     {         /**////刪除該檔案         finfo.Delete();     }     /**////建立唯寫檔案?  using(FileStream fs = finfo.OpenWrite())     {    /**////根據上面建立的檔案流建立寫資料?  StreamWriter w = new StreamWriter(fs);              /**////設定寫資料流的起始位置為檔案流的末尾    w.BaseStream.Seek(0, SeekOrigin.End);              /**////寫入“Log Entry : ”     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();     }  } C#檔案操作:建立HTML檔案**//// 〈summary〉  // 建立HTML檔案  // 〈/summary〉  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());     }  } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.