.net文件的寫入和讀取

aspx部分代碼

<body>
    <form id="form1" runat="server">
    <div>
    <h3>名稱:</h3><input type="text" id="title" runat="server">
     <h3>內(nèi)容:</h3><textarea id="content" runat="server"/>
     <p><asp:button text="寫入內(nèi)容" ID="write_content" runat="server" OnClick="write_content_btn" /></p>
        <asp:label runat="server" ID="display_txt"/>
        <h3>查看內(nèi)容:</h3><asp:button id="see_txt" runat="server" OnClick="see_txt_btn" text="查看內(nèi)容"/>
        <p><asp:label runat="server" id="display_content"/></p>
    </div>
    </form>
</body>

cs部分

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
public partial class inputtxt : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void write_content_btn(object sender, EventArgs e)
    {
        string txtname = title.Value;//獲取輸入的txtname值
        string txtcontent = content.Value;//獲取輸入的txtname值
        string fileurl = @"E:\c\write_in.txt";
        StreamWriter write_in = new StreamWriter(fileurl,false,Encoding.UTF8);//創(chuàng)建寫入文件的對(duì)象,文件位置,是否可以追加內(nèi)容,什么編碼。
        write_in.WriteLine(txtname);
        write_in.WriteLine(txtcontent);
        write_in.Close();
        display_txt.Text = "寫入成功......";
    }
    protected void see_txt_btn(object sender,EventArgs e)
    {
        string fileurl = Server.MapPath("write_in.txt");//將文件路徑賦給字符串filetxt
        if (File.Exists(fileurl))//判斷文件是否存在
        {
            StreamReader readfile = new StreamReader(fileurl, Encoding.UTF8);//創(chuàng)建讀取文件的對(duì)象
            string content = readfile.ReadToEnd();//將讀取到的文件內(nèi)容賦給字符串content,ToEnd從頭讀到尾
            //string content = readfile.Read();讀取到內(nèi)容時(shí)返回一個(gè)正數(shù),沒有內(nèi)容時(shí)返回-1
            //string content = readfile.ReadLine();讀入第一行的內(nèi)容
            readfile.Close();//關(guān)閉文件
            display_content.Text = Server.HtmlDecode(content)+"\n\t";//將讀取出來的內(nèi)容顯示出來
        }
        else
        {
            display_content.Text = "文件不存在!";//文件不存在的顯示
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容