第八章 文件與流處理_第1頁
第八章 文件與流處理_第2頁
第八章 文件與流處理_第3頁
第八章 文件與流處理_第4頁
第八章 文件與流處理_第5頁
已閱讀5頁,還剩50頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

1、1第六章第六章 文件與流處理文件與流處理 文件系統(tǒng)操作文件系統(tǒng)操作 I/O I/O流處理流處理 郵件發(fā)送郵件發(fā)送26.1 6.1 文件與流處理文件與流處理文件系統(tǒng)操作文件系統(tǒng)操作3文件系統(tǒng)操作 在許多ASP.NET Web應(yīng)用程序中,需要處理本地文件系統(tǒng),讀取目錄結(jié)構(gòu),讀寫文件,或者執(zhí)行某些與文件相關(guān)的操作。在.NET框架中,提供了System.IO命名空間用于處理與文件I/O相關(guān)的功能。在該命名空間中包含了許多類,使得文件系統(tǒng)中的目錄與文件處理變得非常容易。 在使用System.IO命名空間中的類的時候,由于ASP.NET應(yīng)用程序是在服務(wù)器上執(zhí)行,因此它所訪問的文件系統(tǒng)就是Web應(yīng)用程序運行

2、的服務(wù)器上的文件系統(tǒng)。4文件系統(tǒng)操作 .NET框架提供了幾個基本的類用于檢索文件系統(tǒng)的信息。這些類都包含在System.IO命名空間中。這些類包括:Directory和File類:這兩個類提供了一些靜態(tài)方法可以檢索服務(wù)器上的文件和目錄。DriveInfo、DirectoryInfo和FileInfo:這些類使用類似的實例方法和屬性檢索相同的信息。 它們的主要區(qū)別在于使用DirectoryInfo或者FileInfo之前,必須先創(chuàng)建其對象實例,而Directory和File類的靜態(tài)方法則是可以直接使用的。 5DriveInfo類 DriveInfo類是.NET 2.0中新增的類。該類增強了以前.

3、NET框架中Directory類中GetLogicalDrives()方法的功能。它可以檢索所有注冊在服務(wù)器上的本地文件系統(tǒng)。通過該類,可以獲取每個驅(qū)動器的名稱、類型、容量和狀態(tài)等信息。6DriveInfo類的主要成員 成員名描述TotalSize獲取驅(qū)動器上存儲空間的總?cè)萘縏otalFreeSpace獲取驅(qū)動器上的可用空閑空間總量AvailableFreeSpace指示驅(qū)動器上的可用空閑空間量DriveFormat返回文件系統(tǒng)的名稱DriveType返回驅(qū)動器類型IsReady返回值表明驅(qū)動器是否已準(zhǔn)備好Name返回驅(qū)動器的名稱VolumeLabel獲取或設(shè)置驅(qū)動器的卷標(biāo)7【例 6 1】 p

4、rotected void Page_Load (object sender, EventArgs e) DriveInfo drive = new System.IO.DriveInfo (C:); lblDriveName.Text = drive.Name; lblDriveType.Text = drive.DriveType.ToString (); lblAvailableFreeSpace.Text = drive.AvailableFreeSpace.ToString (); lblDriveFormat.Text = drive.DriveFormat; lblTotalFr

5、eeSpace.Text = drive.TotalFreeSpace.ToString (); lblTotalSize.Text = drive.TotalSize.ToString (); lblVolumeLabel.Text = drive.VolumeLabel; 8【例 6 2】 void Page_Load (object sender, EventArgs e) foreach (System.IO.DriveInfo drive in System.IO.DriveInfo.GetDrives () TreeNode node = new TreeNode (); node

6、.Value = drive.Name; /在訪問驅(qū)動器之前先檢查IsReady屬性 if (drive.IsReady) node.Text = drive.Name + - (剩余空間: + drive.AvailableFreeSpace + ); else node.Text = drive.Name + - (未就緒); this.TreeView1.Nodes.Add (node); 9Directory和DirectoryInfo類 Directory和DirectoryInfo類提供了一系列有用的方法可以處理與目錄有關(guān)的任務(wù)。Directory類包含許多靜態(tài)方法用于創(chuàng)建、移動和

7、刪除目錄。而DirectoryInfo聲明一個特殊的對象,可以讓用戶在該對象上執(zhí)行與Directory類相同的動作。另外,它還可以列出子目錄和文件。10Directory類的主要方法 方法描述CreateDirectory()創(chuàng)建新的目錄Delete()刪除指定的目錄Exists()確定給定目錄是否存在GetCreationTime()獲取目錄的創(chuàng)建日期和時間GetLastAccessTime()返回上次訪問指定目錄的日期和時間GetLastWriteTime()返回上次寫入指定目錄的日期和時間GetParent()檢索指定路徑的父目錄GetCurrentDirectory()獲取應(yīng)用程序的當(dāng)

8、前工作目錄SetCurrentDirectory()設(shè)置當(dāng)前工作目錄Move()將目錄及其內(nèi)容移到新位置GetAccessControl()返回某個目錄的ACL11DirectoryInfo類的主要方法方法描述Delete()從路徑中刪除DirectoryInfo及其內(nèi)容Refresh()刷新對象的狀態(tài)Create()創(chuàng)建指定目錄MoveTo()將DirectoryInfo實例及其內(nèi)容移動到新路徑CreateSubdirectory()在指定路徑中創(chuàng)建一個或多個子目錄GetDirectories()返回當(dāng)前目錄的子目錄GetFiles()返回當(dāng)前目錄的文件列表12【例 6 3】 創(chuàng)建時間:最后

9、訪問時間:最后修改時間:13【例 6 3】 protected void Page_Load (object sender, EventArgs e) Directory.CreateDirectory (C:asp_dot_net); if (Directory.Exists (C:asp_dot_net) this.Label1.Text = Directory.GetCreationTime (C:asp_dot_net).ToString (); this.Label2.Text = Directory.GetLastAccessTime (C:asp_dot_net).ToStrin

10、g (); this.Label3.Text = Directory.GetLastWriteTime (C:asp_dot_net).ToString (); Directory.Delete (C:asp_dot_net); 14【例 6 4】 void LoadDirectories (TreeNode parent, string path) DirectoryInfo dir = new DirectoryInfo (path); try foreach (DirectoryInfo d in dir.GetDirectories () TreeNode node = new Tre

11、eNode (d.Name, d.FullName); parent.ChildNodes.Add (node); / 對當(dāng)前目錄遞歸調(diào)用本函數(shù) LoadDirectories (node, d.FullName); catch (UnauthorizedAccessException e) parent.Text += (拒絕訪問); catch (IOException e) parent.Text += (位置錯誤: + e.Message + ); 15【例 6 4】void Page_Load (object sender, EventArgs e) DriveInfo drive

12、= new DriveInfo (D:); TreeNode node = new TreeNode (); node.Value = drive.Name; /在訪問驅(qū)動器之前先檢查IsReady屬性 if (drive.IsReady) node.Text = drive.Name + - (剩余空間: + drive.AvailableFreeSpace + ); LoadDirectories (node, drive.Name); else node.Text = drive.Name + - (未就緒); this.TreeView1.Nodes.Add (node);16File

13、和FileInfo類 通過Directory和DirectoryInfo類可以很方便地顯示和瀏覽目錄樹,如果要進一步顯示目錄中的文件列表,可以使用File或者FileInfo類。 File類提供了用于創(chuàng)建、復(fù)制、刪除、移動和打開文件的靜態(tài)方法,并協(xié)助創(chuàng)建FileStream對象。 而FileInfo類提供的是實例方法,其功能與File類類似,也可以創(chuàng)建FileStream對象。FileInfo類是不繼承的。17【例 6 5】 void TreeView1_SelectedNodeChanged (object sender, EventArgs e) System.IO.DirectoryIn

14、fo directory = new System.IO.DirectoryInfo (TreeView1.SelectedNode.Value); GridView1.DataSource = directory.GetFiles (); GridView1.DataBind ();18【例 6 6】 void Page_Load (object sender, EventArgs e) DirectoryInfo dir = new DirectoryInfo (C:); foreach (FileInfo file in dir.GetFiles (*.*) Response.Write

15、 (file.Name); Response.Write (file.LastWriteTime.ToString () +  ); Response.Write (file.Attributes.ToString () + ); 19Path類 雖然,文件和目錄類可以很好地完成文件系統(tǒng)的大部分操作,甚至能夠兼容以前的ASP程序。但是,這些類對于路徑的處理還是顯得不夠完美。在很多情況下,程序員必須處理與路徑相關(guān)的操作。 對于這些與路徑相關(guān)的任務(wù),.NET框架提供了Path類專門用于處理它們。路徑信息是以普通字符串形式存儲的,Path類對包含文件或目錄路徑信息的字符串實例執(zhí)行操作。20P

16、ath類的主要方法 ChangeExtension更改路徑字符串的擴展名。 Combine合并兩個路徑字符串。 GetDirectoryName返回指定路徑字符串的目錄信息。 GetExtension返回指定的路徑字符串的擴展名。 GetFileName返回指定路徑字符串的文件名和擴展名。 GetFileNameWithoutExtension返回不具有擴展名的指定路徑字符串的文件名。 GetFullPath給定一個非根路徑,返回基于當(dāng)前目錄從根目錄開始的絕對路徑。21Path類的主要方法 GetInvalidFileNameChars獲取包含不允許在文件名中使用的字符的數(shù)組。 GetInva

17、lidPathChars獲取包含不允許在路徑名中使用的字符的數(shù)組。 GetPathRoot獲取指定路徑的根目錄信息。 GetTempFileName創(chuàng)建磁盤上唯一命名的零字節(jié)的臨時文件并返回該文件的完整路徑。 GetTempPath返回當(dāng)前系統(tǒng)的臨時文件夾的路徑。 HasExtension確定路徑是否包括文件擴展名。 IsPathRooted是否包含絕對路徑信息22【例 6 7】void Page_Load (object sender, EventArgs e) lblRootPath.Text = Path.GetPathRoot (this.txtPathName.Text); lblD

18、irectoryName.Text = Path.GetDirectoryName (this.txtPathName.Text); lblFileName.Text = Path.GetFileName (this.txtPathName.Text); lblFileNameWithoutExtension.Text = Path.GetFileNameWithoutExtension (this.txtPathName.Text); lblExtension.Text = Path.GetExtension (this.txtPathName.Text);23【例 6 7】 lblTemp

19、oraryPath.Text = Path.GetTempPath (); lblDirectorySeparatorChar.Text = Path.DirectorySeparatorChar.ToString (); lblAltDirectorySeparatorChar.Text = Path.AltDirectorySeparatorChar.ToString (); lblVolumeSeparatorChar.Text = Path.VolumeSeparatorChar.ToString (); lblPathSeparator.Text = Path.PathSeparat

20、or.ToString (); lblInvalidChars.Text = HttpUtility.HtmlEncode (new String (Path.GetInvalidPathChars (); lblInvalidFileNameChars.Text = HttpUtility.HtmlEncode (new String (Path.GetInvalidFileNameChars (); 24文件瀏覽器 利用本章上述的概念,結(jié)合數(shù)據(jù)綁定控件,編寫一個簡單的文件瀏覽器。這在網(wǎng)站維護和管理中是非常重要的功能。 本例不再使用遞歸的方式顯示文件和目錄列表,而是用GridView控件來顯

21、示。25【例 6 8】 26【例 6 8】void ShowDirectoryContents (string path) / 定義當(dāng)前目錄 DirectoryInfo dir = new DirectoryInfo (path); / 獲取DirectoryInfo和FileInfo對象 FileInfo files = dir.GetFiles (); DirectoryInfo dirs = dir.GetDirectories (); / 顯示目錄列表 lblCurrentDir.Text = 當(dāng)前新時目錄: + path; gridFileList.DataSource = file

22、s; gridDirList.DataSource = dirs; Page.DataBind (); / 清楚已選擇項 gridFileList.SelectedIndex = -1; / 記錄當(dāng)前路徑 this.ViewStateCurrentPath = path;27【例 6 8】void Page_Load (object sender, EventArgs e) if (!Page.IsPostBack) ShowDirectoryContents (Server.MapPath (.);void gridFileList_SelectedIndexChanged (object

23、sender, EventArgs e) / 獲取被選文件 string file = (string) gridFileList.DataKeysgridFileList.SelectedIndex.Value; / 把被選文件的FileInfo對象添加到動態(tài)數(shù)組files中 ArrayList files = new ArrayList (); files.Add (new FileInfo (file); / 將files綁定到formFileDetails控件 formFileDetails.DataSource = files; formFileDetails.DataBind ()

24、;28【例 6 8】void cmdUp_Click (object sender, EventArgs e) string path = (string) ViewStateCurrentPath; path = Path.Combine (path, .); path = Path.GetFullPath (path); ShowDirectoryContents (path);void gridDirList_SelectedIndexChanged (object sender, EventArgs e) / 獲取被選目錄 string dir = (string) gridDirLi

25、st.DataKeysgridDirList.SelectedIndex.Value; / 刷新目錄列表和文件列表 ShowDirectoryContents (dir);29I/O流 使用流模型可以執(zhí)行I/O操作。.NET框架在很多處理上使用流模型。本質(zhì)上,流是對數(shù)據(jù)的抽象,使得程序員能夠使用類似的有序字節(jié)流的方式處理不同數(shù)據(jù)。 .NET框架使用流模型讀寫數(shù)據(jù),而無須對不同數(shù)據(jù)源編寫不同代碼。這些模型基于兩個基本的概念:流(Stream)和讀取器/編寫器(Reader/Writer)。所有.NET流都是從System.IO.Stream類派生的。流可以表示內(nèi)存緩沖區(qū)的數(shù)據(jù)、網(wǎng)絡(luò)連接檢索的數(shù)據(jù)

26、以及讀寫文件的數(shù)據(jù)。30.NET I/O流結(jié)構(gòu) 31Stream類的派生類 類描述FileStream支持通過其Seek方法隨機訪問文件。默認(rèn)情況下,F(xiàn)ileStream以同步方式打開文件,但它也支持異步操作。MemoryStreamMemoryStream是一個非緩沖的流,可以在內(nèi)存中直接訪問它的封裝數(shù)據(jù)。BufferedStream是向另一個Stream添加緩沖的Stream。NetworkStream表示網(wǎng)絡(luò)連接上的Stream。DeflateStream提供使用Deflate算法壓縮和解壓縮流的方法和屬性。32文件讀寫 讀寫本地文件,可以使用FileStream類。FileStream

27、 fs = new FileStream (Server.MapPath(Text.txt), FileMode.Open);byte data = new bytefs.Length;fs.Read(data, 0, (int)fs.Length);fs.Close(); 在上述代碼中,首先創(chuàng)建了一個字節(jié)數(shù)組data,其長度由FileStream對象的Length屬性設(shè)定。然后,使用Read方法將流數(shù)據(jù)填充到數(shù)組中。33文件的訪問模式 枚舉值描述Append打開現(xiàn)有文件并查找到文件尾,或創(chuàng)建新文件。Create指定操作系統(tǒng)應(yīng)創(chuàng)建新文件。如果文件已存在,則改寫它。CreateNew指定操作系統(tǒng)

28、應(yīng)創(chuàng)建新文件。Open指定操作系統(tǒng)應(yīng)打開現(xiàn)有文件。OpenOrCreate指定操作系統(tǒng)應(yīng)打開文件(如果文件存在);否則,應(yīng)創(chuàng)建新文件。Truncate指定操作系統(tǒng)應(yīng)打開現(xiàn)有文件。文件一旦打開,就將被截斷為零字節(jié)大小。34【例 6 9】 using System.IO;void Page_Load (object sender, EventArgs e) / 新建FileStream對象,以Append方式打開進行寫入 FileStream fs = new FileStream (Server.MapPath (Text.Txt), FileMode.Append, FileAccess.Wr

29、ite); byte data = System.Text.Encoding.ASCII.GetBytes (This is added by FileStream.Write().); fs.Write (data, 0, (int) data.Length); fs.Flush ();/ 清除fs的緩沖區(qū) fs.Close ();35常用的讀取器和編寫器 類描述TextReader表示可讀取連續(xù)字符系列的讀取器。StreamReader從字節(jié)流中讀取字符,從TextReader派生。StringReader從TextReader類派生,從Strings中讀取字符。BinaryReader從

30、Streams讀取編碼的字符串和基元數(shù)據(jù)類型。TextWriter是StreamWriter和StringWriter的抽象基類。StreamWriter通過使用Encoding將字符轉(zhuǎn)換為字節(jié),向Streams寫入字符。36【例 6 10】 using System.IO;void Page_Load (object sender, EventArgs e) / 新建StreamWriter對象,打開Text.TXT文件 StreamWriter streamwriter = new StreamWriter (File.Open(Server.MapPath (Text.txt), Fil

31、eMode.Open); streamwriter.Write (This line is added by StreamWriter.write().); streamwriter.Close (); / 新建StreamReader對象,打開Text.TXT文件,將內(nèi)容讀入到tmp字符串 StreamReader reader = new StreamReader (File.Open(Server.MapPath (Text.txt), FileMode.Open); string tmp = reader.ReadToEnd (); reader.Close (); Response.

32、Write (tmp);37文件壓縮 .NET 2.0框架引入了一個新的命名空間System.IO.Compression,該命名空間包含用于數(shù)據(jù)壓縮和解壓的類GZipStream和DeflateStream。 在壓縮時,需要把真實的流轉(zhuǎn)換成一個壓縮流。比如,首先創(chuàng)建一個FileStream對象:FileStream fs = new FileStream (c:myfile.txt, FileMode.Create); 接下來,再創(chuàng)建一個GZipStream或者DeflateStream對象:GZipStream cs = new GZipStream(fs, CompressionMode

33、.Compress);38文件壓縮 在寫數(shù)據(jù)時,應(yīng)該使用壓縮流的Write()方法,而不是FileStream的Write()方法。:StreamWriter writer = new StreamWriter(cs); 完成之后,清除壓縮流以結(jié)束文件中的數(shù)據(jù):w.Flush(); fileStream.Close();39文件壓縮 讀取數(shù)據(jù)的操作直接把CompressionMode改為CompressionMode.Decompress:FileStream fs = new FileStream (c:myfile.bin, FileMode.Open);GZipStream ds = n

34、ew GZipStream(fs, CompressionMode.Decompress);StreamReader r = new StreamReader(ds);40【例 6 11】 using System.IO;using System.IO.Compression;void Page_Load(object sender, EventArgs e) / 讀取需要壓縮的文件string f = Server.MapPath(TextFile.txt);FileStream ins = File.OpenRead(f);byte buffer = new byteins.Length;

35、ins.Read(buffer, 0, buffer.Length);ins.Close();/ 創(chuàng)建輸出文件FileStream outs = File.Create(Path.ChangeExtension(f, zip);/ 壓縮輸入流,并把它寫入到輸出流中GZipStream gzip = new GZipStream(outs, CompressionMode.Compress);gzip.Write(buffer, 0, buffer.Length);gzip.Close(); outs.Close ();41序列化 .NET框架還提供了更高級的數(shù)據(jù)存儲方式,即序列化(Serial

36、ization)。序列化模型是建立在流的基礎(chǔ)上的。序列化的過程就是將整個活動的對象轉(zhuǎn)換成有序的字節(jié),然后把這些字節(jié)寫到FileStream之類的流對象中。然后,在下次使用時,可以把它讀出來,創(chuàng)建原始的對象。42序列化過程示意圖 43序列化 對象被序列化為流。流傳遞的不僅是數(shù)據(jù),還包括有關(guān)對象類型的信息,如對象的版本、區(qū)域性和程序集名稱。通過該流,可以將對象存儲在數(shù)據(jù)庫、文件或內(nèi)存中。進行序列化的對象必須符合如下的標(biāo)準(zhǔn):對象的類必須在聲明時前面加上Serializable()屬性類的所有公有和私有變量都必須是可序列化的。如果類是派生的,所有基類都必須是可序列化的。44【例 6 12】 Seria

37、lizable ()public class LogEntry /網(wǎng)頁日志記錄項 private string message; / 回發(fā)的消息 private DateTime date; / 消息的回發(fā)時間 public string Message get return message; set message = value; public DateTime Date get return date; set date = value; public LogEntry (string message) this.message = message; this.date = DateTi

38、me.Now; 45【例 6 12】 private void Log (string message) FileMode mode; if (ViewStateLogFile = null) ViewStateLogFile = c:user.log; mode = FileMode.Create; else mode = FileMode.Append; string fileName = (string) ViewStateLogFile; using (FileStream fs = new FileStream (fileName, mode) LogEntry entry = ne

39、w LogEntry (message); BinaryFormatter formatter = new BinaryFormatter (); formatter.Serialize (fs, entry); 46【例 6 12】void cmdRead_Click (object sender, EventArgs e) if (ViewStateLogFile != null) string fileName = (string) ViewStateLogFile; using (FileStream fs = new FileStream (fileName, FileMode.Op

40、en) BinaryFormatter formatter = new BinaryFormatter (); while (fs.Position fs.Length) LogEntry entry = (LogEntry) formatter.Deserialize (fs); lblInfo.Text += entry.Date.ToString () + ; lblInfo.Text += entry.Message + ;47【例 6 12】void Page_Load (object sender, EventArgs e) if (!Page.IsPostBack) Log (首次載入頁面。); else Log (頁面回發(fā)。);void cmdDelete_Click (object sender, Ev

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論