I have been converting some code from C++ to C#. My lack of understanding of C# API doesnt let me find the equivalent of fprintf. What Im basically trying to do is write a helper class to Log information to a file. So far I have go the following class defined. If someone see something unusual please let me know. The method "Log" only logs strings currently. I dont know if this is the best way to do this. Anyway I would like to convert some numbers to dump into the log file. In C++, I have fprintf doing the conversion. How can I achieve something similar in C# ??
fprintf(file, "Wheel1: %f \t Wheel2: %f \t Dist: %f, Wheel0, Wheel1, TotalDist);
public class Logger
{
private string strPathName = string.Empty;
private StreamWriter sw = null;
/// <summary>
/// Constructor
/// </summary>
/// <param name="prefix"></param>
public Logger(string prefix)
{
DateTime datet = DateTime.Now;
// Format string
if (string.IsNullOrEmpty(prefix))
{
prefix += "_";
}
else
{
prefix = "";
}
strPathName = "Log_" + prefix + datet.ToString("MM_dd_hhmmss") + ".log";
if (File.Exists(strPathName) == true)
{
FileStream fs = new FileStream(strPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Close();
}
}
/// <summary>
/// Create a directory if not exists
/// </summary>
/// <param name="strLogPath"></param>
/// <returns></returns>
private bool CheckDirectory(string strLogPath)
{
try
{
int nFindSlashPos = strLogPath.Trim().LastIndexOf("\\");
string strDirectoryname = strLogPath.Trim().Substring(0, nFindSlashPos);
if (Directory.Exists(strDirectoryname) == false)
{
//LogInfo("Creating log directory :" + strDirectoryname);
Directory.CreateDirectory(strDirectoryname);
}
return true;
}
catch (Exception)
{
return false;
}
}
public void Log(String message)
{
DateTime datet = DateTime.Now;
if (sw == null)
{
sw = new StreamWriter(strPathName, true);
}
sw.Write(message);
sw.Flush();
}
/// <summary>
/// Close stream
/// </summary>
public void Close()
{
if (sw != null)
{
sw.Close();
sw = null;
}
}
}
Thanks in advance
You can create a StreamWriter to wrap your FileStream
, and then use Write
to get something like
StreamWriter writer = new StreamWriter(fs);
writer.Write("Wheel1: {0} \t Wheel2: {1} \t Dist: {2}", Wheel0, Wheel1, TotalDist);
How about:
public void Log(String message, params object[] args)
{
DateTime datet = DateTime.Now;
if (sw == null)
{
sw = new StreamWriter(strPathName, true);
}
sw.Write(String.Format(message,args));
sw.Flush();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With