不同项目模板的常规错误处理消息

时间:2019-05-27 11:44:05

标签: c# error-handling

我有一个下面的类,它将新行写入文本文件。

using System;
using System.Text;
using System.IO;

namespace TextStreamer
{
    class TextWriter
    {
        private string _FilePath;
        private string _TextToAdd;

        // Constructor will assign file Path variable and check if file is valid
        public TextWriter(string filePath)
        {
            this._FilePath = filePath;  
            ValidateFile(); 
        } 

        // Validate if the text file exist
        private void ValidateFile()
        {
            // If file does not exist show error message 
            // and create new text file
            if(!File.Exists(_FilePath))
            {
                Console.WriteLine("File not found");   
                File.Create(_FilePath);
                Console.WriteLine("Created new file {0}", _FilePath);  
            }
        }

        // Write new line to the text file
        public void WriteNewLine(string text)
        {
            this._TextToAdd = text + Environment.NewLine;
            File.AppendAllText(_FilePath, _TextToAdd);
        }
    }
}

现在,如果该文件不存在,它将向控制台写入一条消息,然后它将创建文本文件,但是如果我使用了WPF应用程序,在这种情况下,我宁愿显示带有相同消息的消息框,我该如何实现。

我尝试抛出异常FileNotFoundException,但这只会使程序崩溃并退出。

1 个答案:

答案 0 :(得分:0)

一种简单的方法是使用公共变量将选项更改为控制台日志或显示消息。

为通用消息框添加名称空间:

using System.Windows;

并在您的类中添加一个公共变量,该变量可让您以编程方式更改日志记录方法,例如:

public bool UseMsgBox = false;

您可以通过使用intenum之类的方法来改进此功能,尽管bool仅适用于2个选项。

添加日志记录方法,例如:

private void LogMsg(string msg)
{
    if(UseNsgBox) MessageBox.Show(msg);
    else Console.WriteLine(msg);
}

然后将Console.WriteLine替换为LogMsg

在创建课程时,请确保更改选项:

TextWriter textWriter = new TextWriter("SomeFile.txt");
textWriter.UseMsgBox = true; // or false

实际上,当您创建类时立即调用LogMsg时,这可能不起作用,因此也可能将其添加为初始化参数:

 public TextWriter(string filePath, bool useMsgBox = false)
 {
     UseMsgBox = useMsgBox;
     // ...
 }