C#相当于fprintf

nix*_*get 4 c# printf class equivalent

我一直在将一些代码从C++转换为C#.我对C#API缺乏了解并不能让我找到相当于fprintf的东西.我基本上要做的是编写一个帮助类来将信息记录到文件中.到目前为止,我已经定义了以下类.如果有人看到不寻常的东西,请告诉我."Log"方法目前仅记录字符串.我不知道这是否是最好的方法.无论如何,我想将一些数字转换为转储到日志文件中.在C++中,我有fprintf进行转换.我怎样才能在C#中实现类似的东西?

fprintf(file, "Wheel1: %f \t Wheel2: %f \t Dist: %f, Wheel0, Wheel1, TotalDist);
Run Code Online (Sandbox Code Playgroud)
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;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ada*_*cin 5

你可以创建一个StreamWriter来包装你的FileStream,然后Write用来获得类似的东西

StreamWriter writer = new StreamWriter(fs);
writer.Write("Wheel1: {0} \t Wheel2: {1} \t Dist: {2}", Wheel0, Wheel1, TotalDist);
Run Code Online (Sandbox Code Playgroud)