如何在单个txt文件中保存多个异常? [英] How to save multiple exception in a single txt file?

查看:79
本文介绍了如何在单个txt文件中保存多个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FileStream fs1 = new FileStream("D:\\Error.txt", FileMode.OpenOrCreate,
 FileAccess.Write);
StreamWriter writer = new StreamWriter(fs1);
 // If file exists, text will be appended ; otherwise a new file will be created
writer.Write(string.Format("Message: {0}<br />{1}StackTrace :{2}{1}Date :{3}{1}-----------------------------------------------------------------------------{1}",
 ex.Message, Environment.NewLine, ex.StackTrace, DateTime.Now.ToString()));
  writer.Close();

//this code segment read data from the file.
 FileStream fs2 = new FileStream("D:\\Error.txt", FileMode.OpenOrCreate,
 FileAccess.Read);
 StreamReader reader = new StreamReader(fs2);
 reader.Close();



这里是我的代码,用更新的最后一个异常保存异常..如何保存多个异常


Here my code, save the exception with updated last exception..how to save multiple exceptions


推荐答案

取消OpenOrCreate,它会丢弃以前的任何文件内容。



首选,使用 File.AppendAllText 替换整个FileStream代码[ ^ ] - 它打开文件,附加新文本,然后在一行中再次关闭文件。并且它不会使FileStream对象(fs1)处于不适当的位置。



也可以使用File.ReadAllText而不是单独的流。
Take off the OpenOrCreate, which discards any previous file content.

By preference, replace the whole FileStream code with File.AppendAllText[^] - it opens teh file, appends the new text, and closes the file again in a single line. And it doesn't leave a FileStream object (fs1) sitting there undisposed.

Use File.ReadAllText as well instead of separate streams there as well.


试试这个



try this

string path ="D:\\Error.txt";
           File.AppendAllLines(path , new string[] { string.Format("Message: {0}<br />{1}StackTrace :{2}{1}Date :{3}{1}-----------------------------------------------------------------------------{1}",
          ex.Message, Environment.NewLine, ex.StackTrace, DateTime.Now.ToString()});
        string[] lines =  File.ReadAllLines(path);





使用文件.AppendAllLines [ ^ ]


这篇关于如何在单个txt文件中保存多个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆