tobbbe
8/12/2014 - 12:59 PM

C# log to file

C# log to file

// best. can also be used in razor view if you wrap with the @function as below
@functions
{
    private string _path = null;
    
    public string LogPath
    {
        get
        {
            return _path ?? (_path = Request.MapPath("/klarna.log"));
        }
    }
    
    public void Log(string message)
    {
        System.IO.File.AppendAllText(LogPath, DateTime.Now.ToString() + ": " + message + Environment.NewLine);
    }
    
    public void Log(string format, params object[] values)
    {
        Log(string.Format(format, values));
    }
}


namespace CustomShippingProject
{
    public static class plzhelp
    {

        public static void Logger(string lines)
        {
            // Write the string to a file.append mode is enabled so that the log
            // lines get appended to  test.txt than wiping content and writing the log
            string filenameA = HttpContext.Current.Server.MapPath("~/test.txt");

            System.IO.StreamWriter file = new System.IO.StreamWriter(filenameA, true);
            file.WriteLine(lines);

            file.Close();

        }