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(); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?