2016-07-14 4 views
0

확인란을 선택하면 로그를 작성하는 확인란을 만들려고했습니다.C# checkbox 로그 파일 쓰기

그러나 나는 많은 문제가있어 내가 다음에해야할 일을 잘 모른다. 그래서 코드를 엉망으로 만든다.

이미지를 보면 로그를 작성하고 IP 주소를 입력 한 다음 "핑 (Ping)!"을 클릭하면 로그를 작성하는 확인란이 있습니다. 버튼을 누른 다음 ping을 수행하고 로그 파일을 c : \ Logs \에 sametime으로 작성해야합니다.

enter image description here

내 코드 : "정지"

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Threading; 
using System.IO; 
using System.Diagnostics; 
using System.Net; 

namespace PingProgramm 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     Thread th; 
     private void button1_Click(object sender, EventArgs e) 
     { 
      if(checkBox1.Checked) 
      { 

      } 
      th = new Thread(thread1); 
      th.Start(); 
     } 

     public void thread1() 
     { 
      try 
      { 
       string command = "/c ping -t " + textBox1.Text; 
       ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command); 
       Process proc = new Process(); 
       proc.StartInfo = procStartInfo; 
       procStartInfo.RedirectStandardOutput = true; 
       procStartInfo.RedirectStandardInput = true; 
       procStartInfo.RedirectStandardError = true; 
       procStartInfo.UseShellExecute = false; 
       procStartInfo.CreateNoWindow = true; 
       proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); 
       proc.Start(); 
       proc.BeginOutputReadLine(); 
       proc.WaitForExit(); 
      } 
      catch (Exception) 
      { 
       //if an error occurs with in the try block, it will handled here. 
      } 
     } 
     void proc_OutputDataReceived(object sender, DataReceivedEventArgs e) 
     { 
      if (stop) 
      { 
       var proc = (Process)sender; 

       stop = false; // allows you to spawn a new thread after stopping the first 
       proc.SynchronizingObject = this; // puts the form in charge of async communication 
       proc.Kill(); // terminates the thread 
       proc.WaitForExit(); // thread is killed asynchronously, so this goes here... 

      } 
      if (e.Data != null) 
      { 
       string newLine = e.Data.Trim() + Environment.NewLine; 
       MethodInvoker append =() => richTextBox1.Text += newLine; 
       richTextBox1.BeginInvoke(append); 
      } 
     } 
     bool firstTime = true; 
     private void textBox1_Click(object sender, EventArgs e) 
     { 
      if (firstTime) 
      { 
       firstTime = false; 
       textBox1.Clear(); 
      } 
     } 

     bool stop = false; 
     private void button2_Click(object sender, EventArgs e) 
     { 
      stop = true; 
     } 

     public static void WriteLog(string strLog) 
     { 
      StreamWriter log; 
      FileStream fileStream = null; 
      DirectoryInfo logDirInfo = null; 
      FileInfo logFileInfo; 

      string logFilePath = "C:\\Logs\\"; 
      logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt"; 
      logFileInfo = new FileInfo(logFilePath); 
      logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName); 
      if (!logDirInfo.Exists) logDirInfo.Create(); 
      if (!logFileInfo.Exists) 
      { 
       fileStream = logFileInfo.Create(); 
      } 
      else 
      { 
       fileStream = new FileStream(logFilePath, FileMode.Append); 
      } 
      log = new StreamWriter(fileStream); 
      log.WriteLine(strLog); 
      log.Close(); 
     } 

     private void checkBox1_CheckedChanged(object sender, EventArgs e) 
     { 

     } 

    } 
} 

내가 클릭하면 버튼을 클릭하면 핑 (ping)이 중지되고 로그 쓰기가 중지됩니다.

행복을 빌며,

KLDesigns

+1

하는 방법에 대해? 어떤 예외로 코드가 실패합니까? – Lara

+0

그것은 뭔가 잘못되었거나 무언가를 말하지 않지만 내 방법은 어떻게 든 시도하지 않으면 작동하지 않습니다. – KLDesigns

+0

코드를 디버깅하는 방법을 알고 있습니까? 예외 처리는 어떻습니까? 자신에게 기꺼이하지 않는 한 아무도 당신을 도울 수 없습니다. – Lara

답변

0

이 줄을 변경해보십시오 : 유 디버깅을 시도 했

MethodInvoker append =() => richTextBox1.Text += newLine; 

MethodInvoker append =() => { 
     richTextBox1.Text += newLine; 
     if (checkBox1.Checked) 
     { 
      WriteLog(newLine); 
     } 
    }; 
+0

오류 \t CS0103 \t 이름 'WriteLine'이 (가) 현재 컨텍스트에 존재하지 않습니다. – KLDesigns

+0

미안하지만 WriteLog는 대답이 업데이트되었습니다. –

+0

정말 고마워요! – KLDesigns