C#文件的读写
读文件
使用文件流的形式,StreamRead中的ReadLine方法,需要注意的是路径也可以选用相对路径
// 创建一个 StreamReader 的实例来读取文件
// using 语句也能关闭 StreamReader
using (StreamReader sr = new StreamReader("c:/jamaica.txt"))
{
string line;
// 从文件读取并显示行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
写文件
StreamWriter中的WriteLine方法,需要注意的是路径也可以选用相对路径
using (StreamWriter sw = new StreamWriter(System.Windows.Forms.Application.StartupPath + "\\access_path.txt"))
{
//sw.Write("要保存到文件中的数据");//写一行无换行符
sw.WriteLine("要保存到文件中的数据");//把行结束符写入到文本字符串或流
sw.Flush();
}
判断文件是否存在,创建文件
有时读文件的时候需要判断文件是否存在:System.Windows.Forms.Application.StartupPath为软件运行的路径。注意后面加文件名的时候添加“\”
if(File.Exists(System.Windows.Forms.Application.StartupPath+"\\access_path.txt"))
{
StreamReader sr = new StreamReader(System.Windows.Forms.Application.StartupPath + "\\access_path.txt", Encoding.Default);
string content = sr.ReadLine();//此处只读取文件中一行数据
sr.Close();
}
else
{
using (File.Create(System.Windows.Forms.Application.StartupPath + "\\access_path.txt"))
{
//创建文件后的操作 可为空
}
}
删除文件
File.Delete(filePath);