ASP.NET建立檔案並寫入內容

來源:互聯網
上載者:User
asp.net|建立 在ASP.NET中,檔案處理的整個過程都是圍繞著System.IO 這個名稱空間展開的。這個名稱空間中具有執行檔案讀、寫所需要的類。本文從最基本的操作開始,解釋在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方法時,將要被讀取的文字檔的結尾處會用一個Null 字元串("")來標記。
現在開始編寫代碼從前面建立的aspnet.txt 檔案中讀取內容:
readfile.aspx
<%@ Import Namespace="System.IO" %>
<%
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



<%@ Import Namespace="System.IO" %>
<%
File.Delete("c:aspnet.txt" )
Response.write("The File aspnet is deleted successfully !!!" )
%>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.