写了个C#读写txt文件的程序,记录一下读写txt文件的类:一行一行读写,读写的内容保存在list里面,如出现异常向调用函数抛出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace parameterToTxt.ToTXT
{
class TXT
{
/// <summary>
/// 读txt文件
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>txt文件内容</returns>
public List<string> Read(string path)
{
StreamReader sr;
try
{
sr = new StreamReader(path, Encoding.Default);
List<string> fileBuf = new List<string>();
string line;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
fileBuf.Add(line);
Console.WriteLine(line.ToString());
}
sr.Close();//关闭读取流文件
return fileBuf;
}
catch (Exception e)
{
//sr.Close();//关闭读取流文件
//Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+"读取"+path+"文件出错:\r\n"+e.ToString());
//return null;
throw e;
}
}
/// <summary>
/// 写数据到txt
/// </summary>
/// <param name="path">写入的文件路劲</param>
/// <param name="buff">写入的内容</param>
public void Write(string path,List<string> buff)
{
try
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
foreach (string line in buff)
{
//开始写入
sw.WriteLine(line);
}
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
catch (Exception e)
{
throw e;
}
}
}
}
调用实例:
public void WriteToFile(List<string> buf)
{
try
{
string filePath = SelectFilePath();
/*List<string> buf = new List<string>();
buf.Add("test第一行");
buf.Add("test第二行");
buf.Add("test第三行");
buf.Add("");
buf.Add("test第五行");*/
if (filePath != "")
{
TXT txt = new TXT();
txt.Write(filePath,buf);
MessageBox.Show("导出文件成功!", "提示");
}
}
catch (Exception e)
{
MessageBox.Show(e.Message,"导出txt文件出错");
}
}
选择保存文件路径的代码:
/// <summary>
/// 选择保存excel文件的路径
/// </summary>
/// <returns></returns>
public string SelectFilePath()
{
string filePath = "";
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存txt文件";
sfd.Filter = "txt文件(*.txt)|*.txt|所有文件|*.*";
sfd.FilterIndex = 1;//指定列表框中的默认选项。
sfd.ValidateNames = true;//验证用户输入是否是一个有效的Windows文件名。
//sfd.CheckFileExists = true;//验证文件有效性(是否存在)。
sfd.CheckPathExists = true;//验证路径有效性。
sfd.RestoreDirectory = true;//保存对话框是否记忆上次打开的目录
sfd.FileName = "equations" + DateTime.Now.ToString("MMddHH");
//设置默认的文件名
//sfd.DefaultFileName = "YourFileName";// in wpf is sfd.FileName = "YourFileName";
if (sfd.ShowDialog() == DialogResult.OK)
filePath = sfd.FileName;
}
catch (Exception e)
{
MessageBox.Show("SelectFilePath:" + e.Message, "警告");
}
return filePath;
}