web-dev-qa-db-ja.com

例外をtxtファイルに保存する方法は?

public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
    DataTable GetListID = new DataTable();
    try
    {
        SqlParameter[] arParams = new SqlParameter[4];

        arParams[0] = new SqlParameter("@Date", typeof(DateTime));
        arParams[0].Value = objFeedRetPL.requestdate;

    }
    catch (Exception ex)
    {
        string dir = @"C:\Error.txt";  // folder location
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
            File.AppendAllText(Server.MapPath("~/Error.txt"), "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
       "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            string New = Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine;
            File.AppendAllText(Server.MapPath("~/Error.txt"), New);
        }
    }
}

ここでは、「C:\」に例外を保存します。

22
Sambasiva

例外を_C:\Error.txt_に保存するため、_Directory.Exists_、_Directory.CreateDirectory_、またはServer.MapPath("~/Error.txt")は必要ありません。単純に StreamWriter を次のように使用できます。

_string filePath = @"C:\Error.txt";

Exception ex = ...

using( StreamWriter writer = new StreamWriter( filePath, true ) )
{
    writer.WriteLine( "-----------------------------------------------------------------------------" );
    writer.WriteLine( "Date : " + DateTime.Now.ToString() );
    writer.WriteLine();

    while( ex != null )
    {
        writer.WriteLine( ex.GetType().FullName );
        writer.WriteLine( "Message : " + ex.Message );
        writer.WriteLine( "StackTrace : " + ex.StackTrace );

        ex = ex.InnerException;
    }
}
_

上記のコードは、存在しない場合は_C:\Error.txt_を作成し、既に存在する場合は_C:\Error.txt_を追加します。

59
ekad
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    namespace ErrorLoggingSample
    {
     class Program
      {
      static void Main(string[] args)
      {
        try
        {
            string str = string.Empty;
            if (string.IsNullOrEmpty(str))
            {
                throw new Exception("Wrong Data");
            }
        }
        catch (Exception ex)
        {
            ErrorLogging(ex);
            ReadError();
        }

    }

    public static void ErrorLogging(Exception ex)
    {
        string strPath = @"D:\Rekha\Log.txt";
        if (!File.Exists(strPath))
        {
            File.Create(strPath).Dispose();
        }
        using (StreamWriter sw = File.AppendText(strPath))
        {
            sw.WriteLine("=============Error Logging ===========");
            sw.WriteLine("===========Start============= " +       DateTime.Now);
            sw.WriteLine("Error Message: " + ex.Message);
            sw.WriteLine("Stack Trace: " + ex.StackTrace);
            sw.WriteLine("===========End============= " + DateTime.Now);

        }
    }

    public static void ReadError()
    {
        string strPath = @"D:\Rekha\Log.txt";
        using (StreamReader sr = new StreamReader(strPath))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
      }
   }
  }
7
RekhaShanmugam

これを試して

 try
    {
        int i = int.Parse("Prashant");
    }
    catch (Exception ex)
    {
        this.LogError(ex);
    }

   private void LogError(Exception ex)
   {
    string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
    message += Environment.NewLine;
    message += "-----------------------------------------------------------";
    message += Environment.NewLine;
    message += string.Format("Message: {0}", ex.Message);
    message += Environment.NewLine;
    message += string.Format("StackTrace: {0}", ex.StackTrace);
    message += Environment.NewLine;
    message += string.Format("Source: {0}", ex.Source);
    message += Environment.NewLine;
    message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
    message += Environment.NewLine;
    message += "-----------------------------------------------------------";
    message += Environment.NewLine;
    string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
    using (StreamWriter writer = new StreamWriter(path, true))
    {
        writer.WriteLine(message);
        writer.Close();
    }
}
1
PK-1825

私はそれを使います

catch (Exception e)
{
    new MessageWriteToFile(e).WriteToFile();
}


public class MessageWriteToFile
{
    private const string Directory = "C:\\AppLogs";
    public string Message { get; set; }
    public Exception Exception { get; set; }
    public string DefaultPath
    {
        get
        {
            var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            var folder = $"{Directory}\\{appName}";

            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }

            var fileName = $"{DateTime.Today:yyyy-MM-dd}.txt";
            return $"{Directory}\\{appName}\\{fileName}";
        }
    }

    public MessageWriteToFile(string message)
    {
        Message = message;
    }

    public MessageWriteToFile(Exception ex)
    {
        Exception = ex;
    }

    public bool WriteToFile(string path = "")
    {
        if (string.IsNullOrEmpty(path))
        {
            path = DefaultPath;
        }

         try
        {
            using (var writer = new StreamWriter(path, true))
            {
                writer.WriteLine("-----------------------------------------------------------------------------");
                writer.WriteLine("Date : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                writer.WriteLine();

                if (Exception != null)
                {
                    writer.WriteLine(Exception.GetType().FullName);
                    writer.WriteLine("Source : " + Exception.Source);
                    writer.WriteLine("Message : " + Exception.Message);
                    writer.WriteLine("StackTrace : " + Exception.StackTrace);
                    writer.WriteLine("InnerException : " + Exception.InnerException?.Message);
                }

                if (!string.IsNullOrEmpty(Message))
                {
                    writer.WriteLine(Message);
                }

                writer.Close();
            }
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}
0
Ergin Çelik