1.读取文件方法:
public static void Read(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader srIn = new StreamReader(fs, Encoding.Default))
{
string strLineIn = "";
//读txt文件,并把配置信息写入内存
while (!srIn.EndOfStream)
{
strLineIn = srIn.ReadLine();//下一行
strLineIn = strLineIn.Trim();
//string[] Array_Msg = strLineIn.Split(',');//输入端配置文件一行的数据
//string temp = Array_Msg[0] + "," + Array_Msg[1];
//Dic_info.Add(temp, strLineIn);
//DicX.Add(temp, Convert.ToInt32(Array_Msg[0]));
//DicY.Add(temp, Convert.ToInt32(Array_Msg[1]));
}
}
}
}
2.写入文件方法:
public static void Write(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
//读txt文件,并把配置信息写入内存
for (int i = 0; i < setIO.Count; i++)
{
sw.WriteLine(setIO[i]);
}
}
}
}
3.写入日志文件,生成日期文件夹:
object locker = new object();
public void WriteLog(string filePath, string strdata)
{
lock (locker)
{
try
{
if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
var date = DateTime.Now;
var temp = string.Format("{0}\\{1}", filePath, date.ToString("yyyyMM"));
if (!Directory.Exists(temp)) Directory.CreateDirectory(temp);
string tempfile = string.Format("{0}\\{1}.csv", temp, date.ToString("yyyyMMdd"));
if (!File.Exists(tempfile))
{
File.Create(tempfile);
}
string msg = string.Format("{0},{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), strdata);
using (StreamWriter sw = new StreamWriter(tempfile, true,Encoding.Default))
{
sw.WriteLine(msg);
}
}
catch (Exception ex)
{
WriteLog(ex);
}
}
}
4.读取文件数据到数据表:
public static DataTable ReadMessage(string path)
{
DataTable dt = new DataTable();
DataColumn col = new DataColumn("时间", typeof(string));
dt.Columns.Add(col);
col = new DataColumn("描述", typeof(string));
dt.Columns.Add(col);
try
{
using (StreamReader srIn = new StreamReader(path, Encoding.Default))
{
string msg;
while (!srIn.EndOfStream)
{
msg = srIn.ReadLine();//下一行
string[] listIn;// = new string[7];
listIn = msg.Split(',');
if (listIn.Length < 2)
continue;
DataRow row = dt.NewRow();
row[0] = listIn[0];
row[1] = listIn[1];
dt.Rows.Add(row);
}
}
}
catch (Exception ex )
{
Log.LogManager.WriteLog(ex);
}
return dt;
}