C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > 文本文件

C# 创建文本文件写入读取实现代码

作者:

C# 创建文本文件写入读取,可以用来做系统日志或程序操作日志或者错误记录,需要的朋友可以参考下。

第一次运行时:

image

第二次运行时:

image

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace 文件操作
{
class Program
{
static void Main(string[] args)
{
//创建一个文本文件,最好先判断一下
StreamWriter sw;
if (!File.Exists("templog.txt"))
{
//不存在就新建一个文本文件,并写入一些内容
sw = File.CreateText("templog.txt");
sw.Write("第一个字");
sw.WriteLine(" 跟随老大的.");
sw.WriteLine("当前日期是:");
sw.WriteLine(DateTime.Now);
}
else
{
//如果存在就添加一些文本内容
sw = File.AppendText("templog.txt");
for (int i = 0; i < 10; i++)
{
sw.WriteLine("可以像平时输出到屏幕一样输出{0}", i);
}
}
sw.Close();
//创建一个读取器
StreamReader sr = new StreamReader("templog.txt");
//一次性读取完
Console.WriteLine(sr.ReadToEnd());
Console.ReadLine();
}
}
}

您可能感兴趣的文章:
阅读全文