2012-03-02 107 views
3

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

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

如何:

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

将这项工作,如果它是一个正常的字符串没有任何格式的?换句话说,没有数字,只是一个普通的字符串。 – nixgadgets 2012-03-02 00:36:12

+0

好吧,我认为我有一个相当好的主意..谢谢一堆 – nixgadgets 2012-03-02 00:54:21

3

这听起来像你正在寻找String.Format

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

4

您可以创建一个StreamWriter来包装你FileStream,然后用Write要达到这样的

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