C#写文件(.csv和.txt)

本文介绍了如何使用C#实现CSV和TXT文件的流式写入,包括StreamWriter的实例化、文件路径管理、时间命名规则,并强调了UTF-8编码的应用。

1、写格式为.csv的方式

StreamWriter txtLog;
txtLog = new StreamWriter(File_txtPath, true, Encoding.UTF8);
if (!File.Exists(File_txtPath))
    File.Create(File_txtPath).Close();
txtLog.Write(strRS + ",");	//中间逗号表示不换行
txtLog.Write(Data + "\r\n");
txtLog.Flush();
txtLog.Close();

在这里插入图片描述2、写格式为txt的方式

StreamWriter swlog;//实例化StreamWriter
public void Writetxt(string str)
{
    swlog = new StreamWriter(@".\Log.txt", true, Encoding.Default);
    //开始写入
    // sw.WriteLine(str);
    swlog.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")+"   "+ str);
    //清空缓冲区
    swlog.Flush();
    //关闭流
    swlog.Close();
   // fs.Close();
}

在这里插入图片描述
文件命名
以时间为节点命名:

string  FilePath=@"E:\Test";
DateTime dateTime=DateTime.Now;
if(!Directory.Exits(FilePath))
    Directory.CreateDirectory(FilePath);
FilePath=string.Format(FilePath + "\\{0:D4}{1:D2}{2:D2}{3:D2}{4:D2}{5:D2}.txt", dateTime.Year, dateTime.Month, dateTime.Day , dateTime.Hour, dateTime.Minute, dateTime.Second);
swlog = new StreamWriter(FilelName, true, Encoding.UTF8);
//开始写入
swlog.Write(strData);
//清空缓冲区
swlog.Flush();
//关闭流
swlog.Close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值