C#相当于fprintf

时间:2012-03-02 00:28:07

标签: c# class equivalent printf

我一直在将一些代码从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;
        }
    }

}

提前致谢

3 个答案:

答案 0 :(得分:5)

您可以创建StreamWriter来封装FileStream,然后使用Write来获取类似

的内容
StreamWriter writer = new StreamWriter(fs);
writer.Write("Wheel1: {0} \t Wheel2: {1} \t Dist: {2}", Wheel0, Wheel1, TotalDist);

答案 1 :(得分:3)

听起来你正在寻找String.Format

Write()WriteLine()方法实际上做同样的事情。

答案 2 :(得分:3)

怎么样:

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