首页 > 学院 > 开发设计 > 正文

c#读取/写入文件

2019-11-17 03:48:52
字体:
来源:转载
供稿:网友

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    PRotected void Page_Load(object sender, EventArgs e)
    {

    }

    /**//// <summary>
    /// 检查文件是否存在
    /// </summary>
    /// <param name="FilePath"></param>
    private void ExistsFile(string FilePath)
    {
        if (!File.Exists(FilePath))
        {
            File.Create(FilePath);
        }
    }

    //读取文件
    protected void Button2_Click(object sender, EventArgs e)
    {
        ExistsFile(Server.MapPath("~/test/111.txt"));
        //读取文件asp.net
        StreamReader sr = new StreamReader(Server.MapPath("~/test/111.txt"), System.Text.Encoding.Default);
        try
        {
            string input = sr.ReadToEnd();
            sr.Close();
            input = input.Replace("<br>", "/r/n");
            Response.Write("<b>文件读取成功!</b>");
            TextBox1.Text = input;
        }
        catch
        {
            Response.Write("<b>文件读取失败!</b>");
        }

    }

    //写入文件
    protected void Button1_Click(object sender, EventArgs e)
    {
        ExistsFile(Server.MapPath("~/test/111.txt"));
        //写入文件
        StreamWriter sw = new StreamWriter(Server.MapPath("~/test/111.txt"), false, System.Text.Encoding.Default);
        try
        {
            sw.Write(TextBox1.Text);
            sw.Close();
            Response.Write("<b>文件写入成功!</b>");
        }
        catch
        {
            Response.Write("<b>文件写入失败!</b>");
        }
    }
}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表