public ActionResult Index2()
{
Class1 class1 = new Class1();
try
{
DataTable dt = new DataTable();
dt.Rows.Add("12", "13");
}
catch (Exception e)
{
string erronstring= class1.logaction(e);//放入try catch中,记录logfile
}
return View();
}
public class Class1
{
public string logaction(Exception e)
{
string Url = HttpContext.Current.Request.Url.ToString();//网址运行地址
string ErrorMsg = e.Message;
string[] drives = Directory.GetLogicalDrives();//获得pc盘的磁盘数组
string path = (drives.Length > 1 ? drives[1] : drives[0]) + @"AALog\";
string year = DateTime.Now.ToString("yyyy");
string month = DateTime.Now.ToString("MM");
string day = DateTime.Now.ToString("dd");
path += @"AAErrorLog\" + year + month;
string filename = @"\" + year + month + day + ".txt";
if (!Directory.Exists(path))//目录是否存在
{
Directory.CreateDirectory(path);
}
path += filename;
//路径合成,路径部分后不需要带\,
//string systemurl = @"D:/AALog";
//string SYSTEMFIE= @"AAErrorLog\" + year + month;
//systemurl = Path.Combine(systemurl, SYSTEMFIE);systemurl=D:/AALog/AAErrorLog/year month
if (!File.Exists(path))//判断文件是否存在
{
File.Create(path).Close();
}
StreamWriter writer = new StreamWriter(path, true);//true追加写文件,之前的保留继续写入,如果不写的话,之前都将被覆盖
string date = DateTime.Now.ToString();
writer.WriteLine("\r\n" + date);
writer.WriteLine("URL:\t" + Url);
writer.WriteLine("Message:");
writer.WriteLine(ErrorMsg);
writer.WriteLine();
writer.Close();//将缓冲区清除,将文本写入基础流中
//Test内容,Logfile就此结束,以下内容跟logfile没有关系
string longlong = "";
List<string> lststring = new List<string>();
char[] buffer = new char[512];
StreamReader reader= new StreamReader(path);
int countreader = reader.Read(buffer, 0, 25);//移动光标索引右移,影响ReadLine()内容,读取当前行(内容不全面)再继续读取下一行
for (int i = 0; i < countreader; i++)
{
longlong += buffer[i];
}
while ( !reader.EndOfStream )//判断是否在文本结尾,返回bool型
{
string readlineone = reader.ReadLine();
lststring.Add(readlineone);
}
reader.Close();//将缓冲区清除,将文本写入基础流中
return ErrorMsg;
}
}
如果读取文件内容是判断条件为
while (str.ReadLine() != null)
{
string readlineone = str.ReadLine();
lststring.Add(readlineone);
}
lststring只保留偶行数的内容,因为在while中时str.ReadLine()已经在读取了一行,下标加一,再str.ReadLine()保留当前行数内容,直接跳过奇数行。