天天看點

ASP.NET建立檔案并寫入内容

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chinahuyong/article/details/2573323

本文從最基本的操作開始,解釋在ASP.NET中檔案處理的概念,包括如從一個檔案中讀取内容、如何向一個檔案中寫入内容和如何删除一個檔案。

  前面已經提到,要想在ASP.NET 頁面中進行檔案處理,必須要有"System.IO"名稱空間。是以,第一步就是引入這個名稱空間:

  < %@ Import Namespace="System.IO" %>

  下一步,就是建立一個文本檔案,并将這個文本檔案配置設定給一個流書寫對象,這樣就可以向文本檔案中寫入内容了。用以下一段代碼來完成這個任務:

  writefile.aspx

   < %@ Import Namespace="System.IO" %>

  < %

  Response.write("Writing the content into Text File in ASP.NET< BR>")

  "聲明流書寫對象

  Dim strwriterobj As StreamWriter

  " 建立文本檔案,配置設定textfile對象

  strwriterobj= File.CreateText("c:aspnet.txt" )

  " 寫入内容

  strwriterobj.WriteLine( "Welcome to wonderfull world of ASP.NET Programming" ) "

  完成操作,關閉流對象

  strwriterobj.Close

  Response.write("Done with the creation of text file and writing content into it")

  %>

  這樣就完成了!現在讓我們繼續進行下一個任務,從剛才建立的文本檔案中讀取内容。

  從檔案中讀取内容

  從檔案中讀取内容與向檔案中寫入内容大緻相同,隻是要注意一下下面的兩件事:

  1. 檔案讀取使用StreamReader類

  2. 當使用了Readline方法時,将要被讀取的文本檔案的結尾處會用一個空字元串("")來标記。

  現在開始編寫代碼從前面建立的aspnet.txt 檔案中讀取内容:

在ASP.NET中,檔案處理的整個過程都是圍繞着System.IO 這個名稱空間展開的。這個名稱空間中具有執行檔案讀、寫所需要的類。

  readfile.aspx

  Response.write("Reading the content from the text file ASPNET.TXT< br>")

  " 建立流讀取對象

  Dim streamreaderobj As StreamReader

  " 聲明變量,以存放從檔案中讀取的内容

  Dim filecont As String

  " 打開文本檔案,配置設定給流讀取對象

  streamreaderobj = File.OpenText( "c:aspnet.txt" )

  " 逐行讀取檔案内容

  Do

  filecont = streamreaderobj.ReadLine()

  Response.Write( filecont & "< br>" )

  Loop Until filecont = ""

  " 完成讀取操作後,關閉流讀取對象

  streamreaderobj.Close

  Response.write("< br>Done with reading the content from the file aspnet.txt")

  删除檔案

  在ASP.NET中删除檔案也非常簡單和直覺。System.IO名稱空間中的"File"(檔案)類有一個Delete方法用來删除檔案,它把檔案名作為一個自變量來傳遞。以下代碼就示範了在ASP.NET中進行檔案删除的步驟:

  Filedelete.aspx

  File.Delete("c:aspnet.txt" )

  Response.write("The File aspnet is deleted successfully !!!" )

繼續閱讀