我一直在将一些代码从 C++ 转换为 C#。我对 C# API 缺乏了解并没有让我找到 fprintf 的等价物。我基本上要做的是编写一个帮助类来将信息记录到文件中。到目前为止,我已经定义了以下类。如果有人看到不寻常的东西,请告诉我。方法“Log”当前仅记录字符串。我不知道这是否是最好的方法。无论如何,我想转换一些数字以转储到日志文件中。在 C++ 中,我让 fprintf 进行转换。我怎样才能在 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;
        }
    }

}

提前致谢

最佳答案

怎么样:

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();
}

关于C# 等效于 fprintf,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9526359/

10-17 01:58