Create log file if not exists using C# code

Create log file if not exists using C# code

No comments

 2,470 total views,  58 views today

In this article, we will learn about how to create a log file if not exists using the C# coding. It is essential in any programing languages to know about it – when we work on a big enterprise project, many times we will be in such needs where we need to handle the custom log file apart from the system generated log files in order to troubleshoot the production issue.

Using the below C# code we can create a log file if not exists in the given path:


using System;
using System.IO;

namespace CreateLogFileInDotNet
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");

string logFilePath = @"C:\temp\log.txt";
string logFileText = "Log is Created at";
Program.WriteToLogFile(logFilePath, String.Format("{0} @ {1}", logFileText, DateTime.Now));
Console.WriteLine("Log file has been written successfully !!!");
Console.ReadLine();

}

public static bool WriteToLogFile(string strLogFilePath, string logFileText)
{

//Create a writer object and open the file:
StreamWriter logStreamWriter;
try
{

if (!File.Exists(strLogFilePath))
{
logStreamWriter = new StreamWriter(strLogFilePath);
}
else
{
logStreamWriter = File.AppendText(strLogFilePath);
}

//Write to the file:
logStreamWriter.WriteLine(DateTime.Now);
logStreamWriter.WriteLine(logFileText);
logStreamWriter.WriteLine();
//Close the stream:
logStreamWriter.Close();
return true;

}
catch (Exception exp)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(exp.Message.ToString());
return false;

}
}

}
}

Summary:

In the above code, we have learned how to create the log file in the given path if not exists the file – then in the consequent call we can append this log file – this can be called from any method or function.

See Also

You may also like the below article – how to create a log file using the PowerShell coding: