2017-02-19 98 views
0

我有一個應用程序,我打算記下日誌文件中的代碼內發生的一切。所以爲此,我做了一個名爲FileCreation的wpf項目,我只是簡單地創建一個文件,然後將數據附加到它。我也想在應用程序啓動時保存數據。以下是代碼:錯誤:構造函數的調用

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     Log("Application started on : " + DateTime.Now.ToString("dd-M-yyyy")); 
    } 

    void Log(string data) 
    { 
     string path = @"C:\\Logs\\" + DateTime.Now.ToString("dd-M-yyyy") + ".txt"; 

     if (File.Exists(path)) 
     { 
      using (StreamWriter sw = File.AppendText(path)) 
      { 
       sw.WriteLine(data); 

      } 
     } 
     else 
     { 
      StreamWriter myFile = new StreamWriter(path); 
      myFile.WriteLine(data); 
      myFile.Close(); 


     } 
    } 
} 

所以在上面的代碼中,我創建了一個功能Log它接受字符串數據作爲參數。如果文件沒有被創建,它會創建一個文件,然後將數據追加到它。我也想記錄應用程序何時開始,所以我也想寫它。因此,在InitializeComponent();之後包含Log(),因爲我認爲這是應用程序啓動時初始化的第一件事。但它給我下面的錯誤:

enter image description here

我知道爲什麼這個錯誤是在啓動它不知道什麼是Log()功能,因爲未來。但是,然後在哪裏定義它。我也有一個問題。我首先在我的系統上測試它,並且它工作正常。當我在其他系統上測試它時,只有它給了我這個錯誤。

爲什麼它在我的系統中沒有給我這個錯誤?

我該如何在我的代碼中處理它?

+0

是否有內部異常? –

+0

@YacoubMassad如何檢查它。? –

+0

你可以在Visual Studio中調試你的應用程序嗎?在調試時,您應該能夠查看包括內部異常在內的異常的詳細信息。 –

回答

1

您沒有足夠的權限寫入驅動器C:\或目錄C:\Logs\不存在。

爲了確保這些都是問題與否,打開例外設置Debug.Windows菜單並檢查所有的複選框。

請注意,此異常顯示由於未處理的異常而導致MainWindow構造函數的初始化失敗。您還可以檢查Exception窗口的InnerException部分,以查看代碼的錯誤。

編輯

How can I handle it in my code

您應該處理Dispatcher.UnhandledException方法,例如之前在主窗口InitializeComponent();線。要做到這一點,寫:

Dispatcher.UnhandledException += OnDispatcherUnhandledException; 

這就需要下面的方法:其中

void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) 
    { 
     ShowError("An application error occurred.\nPlease check whether your data is correct and repeat the action. If this error occurs again there seems to be a more serious malfunction in the application.", e.Exception); 

     e.Handled = true; 
    } 

ShowError嘗試過打印內部異常:

public static void ShowError(string message, Exception exp0) 
    { 
     Exception exp1 = exp0.InnerException; 
     Exception exp2 = exp1 != null ? exp1.InnerException : null; 
     Exception exp3 = exp2 != null ? exp2.InnerException : null; 

     string mess = "unfortunately, no message is available."; 
     string moremess = ""; 

     if (message != null) 
     { 
      mess = message; 
      moremess = exp0.Message + "\n\n"; 
     } 
     else if (exp0 != null) 
     { 
      mess = exp0.Message; 
     } 

     Exception exp = exp0.InnerException; 
     while (exp != null) 
     { 
      moremess += exp.Message + "\n\n"; 
      exp = exp.InnerException; 
     } 

     MessageBox.Show(mess + Environment.NewLine + moremess); 
    } 

希望它能幫助。

+0

請參閱此鏈接[Visual Studio 2015中的異常設置](https://blogs.msdn.microsoft.com/visualstudioalm/2015/02/23/the-新的異常的設置窗口,在視覺工作室2015 /) – Ron