Create log file if not exists using C# code

Create log file if not exists using C# code

No comments

 13,703 total views,  7 views today

C#-S: if-else condition
C#-S: if-else condition

In this create log file if not exists using C# article, we will learn about how to create a log file not exist using the C# coding. It is essential in any programing language 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:

Create log file if not exists using C#


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: Create log file if not exists using C#

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: Create log file if not exists using C#

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

 

About Post Author

Do you have a better solution or question on this topic? Please leave a comment