创建新文件,并添加内容
System.IO.File.WriteAllBytes
System.IO.File.WriteAllText
常用的读写文件
新建一个Log.txt文件
引入System.IO名称空间,用文件流
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace StreamWrite
{
class Program
{
static void Main(string[] args)
{
try
{
FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
bool truth = true;
// Write data to file.
sw.WriteLine("Hello to you.");
sw.WriteLine("It is now {0} and things are looking good.",
DateTime.Now.ToLongDateString());
sw.Write("More than that,");
sw.Write(" it's {0} that C# is fun.", truth);
sw.Close();
}
catch (IOException ex)
{
Console.WriteLine("An IOException has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
}
}
}
读取文件,这里介绍StreamReader对象
static void Main(string[] args)
{
string strLine;
try
{
FileStream aFile = new FileStream("Log.txt",FileMode.Open);
StreamReader sr = new StreamReader(aFile);
strLine = sr.ReadLine();
//Read data in line by line
while(strLine != null)
{
Console.WriteLine(strLine);
Line = sr.ReadLine();
}
sr.Close();
}catch (IOException ex)
{
Console.WriteLine("An IOException has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
}
另外对于简单的文档可以直接sr.ReadToEnd()从头读到尾,还有sr.Read() 返回类型char
FileStream aFile = new FileStream("D:\\Log.txt", FileMode.Append, FileAccess.Write);//FileMode.Append, FileAccess.Write设置追加还是覆盖等
StreamWriter sw = new StreamWriter(aFile);
最简单的日志记录
public class Log
{
public static void WriteToLog(string str)
{
try
{
lock (typeof(Log))
{
FileStream aFile = new FileStream("D:\\Log.txt", FileMode.Append);
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine(str);
sw.Close();
}
}
catch { }
}
}
本文介绍了使用C#进行文件操作的方法,包括如何创建、写入、读取文件,并提供了一个简单的日志记录示例。
2101

被折叠的 条评论
为什么被折叠?



