StreamReader抛出异常 [英] StreamReader throwing Exception

查看:106
本文介绍了StreamReader抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我使用以下代码阅读文本文件。

Hi,
I am using the following code for reading a text file.

string filename = Path.Combine(path, comboBox1.SelectedItem.ToString() + ".rbl");

StreamReader sr = new StreamReader(filename);
Rules.Rows.Clear();
string line;
while ((line = sr.ReadLine()) != null)
{

        if (sr.ReadLine().Contains("Bool"))
        {
            string[] line1 = Regex.Split(sr.ReadLine().ToString(), ",");
            if (line1[1] == "And")
            {
                RbAnd.Checked = true;
                RbOr.Checked = false;
            }
            else
            {
                RbAnd.Checked = false;
                RbOr.Checked = true;
            }
        }

        if (sr.ReadLine().Contains(",") && !sr.ReadLine().Contains("Bool"))
        {
            string[] line2 = Regex.Split(sr.ReadLine().ToString(), ",");
            string val1 = line2[0];
            string val2 = line2[1];
            string val3 = "";
            if (line2.Length == 3)
            {
                if (line2[2] != "")
                {
                    val3 = line2[2];
                }
            }

            Rules.Rows.Add(val1, val2, val3);
        }

}
sr.Close();





投掷NullReferenceException异常。任何人都可以帮我找出我的代码中的错误。



and it throwing NullReferenceException. Anyone can help me to find out the error in my code.

推荐答案

我的解决方案:

My Solution:
using (StreamReader sr = new StreamReader(filename))
{
    Rules.Rows.Clear();
    string line;
    while ((line = sr.ReadLine()) != null)
    {

        if (line.Contains("Bool"))
        {
            string[] line1 = Regex.Split(line, ",");
            if (line1[1] == "And")
            {
                RbAnd.Checked = true;
                RbOr.Checked = false;
            }
            else
            {
                RbAnd.Checked = false;
                RbOr.Checked = true;
            }
        }

        if (line.Contains(",") && !line.Contains("Bool"))
        {
            string[] line2 = Regex.Split(line, ",");
            string val1 = line2[0];
            string val2 = line2[1];
            string val3 = string.Empty;
            if (!string.IsNullOrEmpty(line2[2]) && line2.Length.Equals(3))
            {
                val3 = line2[2];
            }
            Rules.Rows.Add(val1, val2, val3);
        }

    }
    sr.Close();
}


是的,确实可以抛出 StreamReader 构造函数(参见文档:在MSDN上StreamReader构造函数(字符串)[ ^ ]。

作为明智的开发人员,您应该处理异常。
Yes, tThe StreamReader contructor may throw, indeed (see the documentation: "StreamReader Constructor (String)" at MSDN[^]).
As wise developer, you should handle the exception.


这篇关于StreamReader抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆