C#创建文本文件

在项目中需要记录日志,要用代码创建一个文本文件,可以不断写入新的文本信息,这里包含了html控件调用C#后台代码,也有后台获取html控件的值的方法,在这里分享给大家

html源码,input控件调用C#后台的方法

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreateFile.aspx.cs" Inherits="FileCreate.Pages.CreateFile" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>文本写入文件</title>
    <style type="text/css">
        #txtarea1
        {
            width: 300px;
            height: 100px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <textarea runat="server" rows="5" cols="10" name="txtcontent" id="txtarea1"></textarea>
    <br />
    <input id="CreBtn" runat="server" type="button" value="记录文本" onserverclick="CreBtn_Click" />
    </div>
    </form>
</body>
</html>

 

C#代码(需要引用System.IO命名空间),后台获取html控件的值,如果文件存在则写入新的数据,否则创建新的文本文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace FileCreate.Pages
{
    public partial class CreateFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void CreBtn_Click(object sender, EventArgs e)
        {
            string txtContent = this.txtarea1.InnerText;  //获取html控件中输入的值
            string FilePath = "C:\\NewFile.txt";          //设置文件路径
            //需要添加using System.IO命名空间        
            //判断文件是否存在,如果存在,则写入新文本,否则创建新文件
            if (File.Exists(FilePath))
            {                
                //读取文本
                StreamReader sr = File.OpenText(FilePath);
                string input = sr.ReadToEnd();
                sr.Close();
                StreamWriter sw = new StreamWriter(FilePath);
                sw.Write(input); //将原文本写入
                sw.WriteLine();  //隔行
                sw.WriteLine(txtContent + "         //" + DateTime.Now.ToString());  //txtcontent 是要写入的数据
                sw.Close();
            }
            else
            {
                FileStream fs = new FileStream(FilePath, FileMode.CreateNew);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(txtContent + "         //" + DateTime.Now.ToString());  //这里是写入的内容             
                sw.Flush();
            }
        }
    }
}

 

 

转载于:https://www.cnblogs.com/Jackie-sky/archive/2012/12/10/2811771.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值