以txt檔案為例學習了ASP.NET檔案的基本操作,下面是代碼,應該很清楚了:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;//引入System.IOusing System.IO;namespace FileTry{ public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //文字檔並不是指副檔名為 .txt 的檔案,只要是以 ASCII 儲存的檔案均可,比如:.aspx、.htm、.css、.ini 等等。 RenameEx(); } /// <summary> /// 讀樣本 /// </summary> private void ReadEx() { //源檔案,必須存在哦 string path1 = Server.MapPath("goo1.txt");//返回與Web伺服器上的指定虛擬路徑相對應的物理檔案路徑 if (File.Exists(path1))//確定指定檔案是否存在,存在返回true,不存在返回false { //File.OpenText 目標不存在時,異常。 using (StreamReader reader = //實現一個System.IO.StreamReader,使其以一種特定的編碼從位元組流中讀取字元 File.OpenText(path1)) //開啟現有UTF-8編碼檔案以進行讀取 { string str = reader.ReadLine();//從當前流中讀取一行字元並將資料作為字串返回 reader.Close();//關閉System.IO.StreamReader對象和基礎流,並釋放與讀取器關聯的所有系統資源 } } } /// <summary> /// 寫樣本 /// </summary> private void WriteEx() { //源檔案,必須存在哦 string path1 = Server.MapPath("goo1.txt"); if (File.Exists(path1)) { //File.CreateText 目標存在時,覆蓋。相當於刪除了原文本的內容 using (StreamWriter writer = File.CreateText(path1)) //建立或開啟一個檔案用於寫入UTF-8編碼的文本 { writer.WriteLine("寫一行內容"); //將後跟行結束符的字串寫入文字資料流 writer.Close(); } } } /// <summary> /// 追加樣本 /// </summary> private void ElseEx() { //源檔案,必須存在哦 string path1 = Server.MapPath("goo1.txt"); if (File.Exists(path1)) { using (StreamWriter writer = File.AppendText(path1))//建立一個System.IO.StreamReader,它將UTF-8編碼文本追到現有檔案,不會刪除原常值內容 { writer.WriteLine("追加一行內容"); writer.Close(); } } } /// <summary> /// 刪樣本(不限定檔案類型) /// </summary> private void DeleteEx() { //源檔案,必須存在哦 string path1 = Server.MapPath("goo1.txt"); if(File.Exists(path1)) { //File.Delete 目標不存在時,跳過。 File.Delete(path1); } } /// <summary> /// 複製檔案 /// </summary> private void CopyEx() { //源檔案,必須存在哦 string path1 = Server.MapPath("goo.txt"); //目標檔案 string path2 = Server.MapPath("goo1.txt"); //File.Copy(Server.MapPath("goo.txt"), Server.MapPath("goo1.txt")); //將現有檔案複製到新檔案。允許覆蓋同名檔案。 /**第一個參數表示源檔案路徑, * 第二個參數表示目標檔案路徑, * 第三個參數表示目標檔案存在時,是否覆蓋。預設為false。 * 如果該值為 false,當目標檔案存在時,會產生異常,而不是跳過複製。--異常為該檔案已存在。 */ if (File.Exists(path1) && !File.Exists(path2)) { File.Copy(path1,path2, true); } } /// <summary> /// 移動檔案 /// </summary> private void MoveEx() { //源檔案,必須存在哦 string path1 = Server.MapPath("goo.txt"); //目標檔案 string path2 = Server.MapPath("document\\goo.txt"); //將指定檔案移到新位置,並提供指定新檔案名稱的選項 //如果目標檔案存在,則會產生異常,而不是跳過移動。 //第一個參數表示源檔案路徑, 第二個參數表示目標檔案路徑,路徑上的檔案夾要確實存在,不然會報錯 if (File.Exists(path1)&&!File.Exists(path2)) { File.Move(path1,path2); } } /// <summary> /// 重新命名檔案 /// </summary> private void RenameEx() { //源檔案,必須存在哦 string path1 = Server.MapPath(@"document\goo.txt"); //目標檔案 string path2 = Server.MapPath(@"document\goo1.txt"); //重新命名檔案的方法和移動檔案的方法完全相同,只要目標檔案和源檔案位於同一檔案夾下且檔案名稱不相同。 if (File.Exists(path1)&&!File.Exists(path2)) { File.Move(path1,path2); } } }}