使用C#写入日志文件

时间:2016-05-19 10:34:27

标签: c# automation

我正在使用JitBit Macro Recorder来创建“机器人”,这可以节省我很多时间。该程序可以使用鼠标和键盘,并通过检查不同的if选项来执行任务,例如“如果在屏幕上找到图像”。

我最新的“bot”大约有900行命令,我想制作一个日志文件,以便在那里找到错误。可悲的是,这个程序没有提供这样的选项,但它让我用c#作为一项任务。我对c#没有经验,但我想,对于有经验的人来说,这很容易做到。

如果我点击执行c#code ,我会收到以下输入字段:

  

重要说明:此代码必须包含一个名为“Program”的类,其静态方法为“Main”!

public class Program
{
    public static void Main()
    {
        System.Windows.Forms.MessageBox.Show("test");
    }
} 

现在我需要两个代码模板:

1。将消息写入桌面上的“bot_log.txt”。

[19.05.2016 - 12:21:09] "Checking if item with number 3 exists..."

数字“3”随每次运行而变化,并且是剪贴板的精确粘贴。

2. 将空行添加到同一个文件

(应将所有内容添加到此文件末尾的新行中。)

1 个答案:

答案 0 :(得分:0)

如果您不知道如何使用C#编程,那么您应该学习它, 如果你想使用答案提供的代码。 如果你想生成时间戳和内容,那么它不会在几分钟内完成,我不认为有人为你的拟合编写了整个代码。通常问题至少应该有一些普遍的兴趣。

反正:
如果您的程序中有RichTextTbox,则此方法有效。 只需要做一个新事件(比如点击按钮)并在其中执行此操作。 (这也发布在这里或在另一个网站上,有轻微的变化)

public static void SaveMyFile(RichTextBox rtb)
    {
        // Create a SaveFileDialog to request a path and file name to save to.
        SaveFileDialog saveLog = new SaveFileDialog();
        // Initialize the SaveFileDialog to specify the RTF extention for the file.
        saveLog.DefaultExt = "*.rtf";
        saveLog.Filter = "RTF Files|*.rtf"; //You can do other extensions here.

        // Determine whether the user selected a file name from the saveFileDialog.
        if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
           saveLog.FileName.Length > 0)
        {
            // Save the contents of the RichTextBox into the file.
            try
            {
                rtb.SaveFile(saveLog.FileName);
            }
            catch 
            {
                MessageBox.Show("Error creating the file.\n Is the name correct and is enough free space on your disk\n ?");
            }
            MessageBox.Show("Logfile was saved successful.");
        }
    }
相关问题