首页 > 解决方案 > 向 csv 阅读器添加错误处理以检测空文件或不正确的数据类型

问题描述

我正在搞乱 csv 文件的写入/读取并附加它们。我有一个由所有相同字符组成的文件,我只是使用布尔运算符返回true它们是否相同或false不同。我如何才能为此添加错误处理,例如,如果文件为空,它将显示一条消息而不会崩溃。或者如果文件中有整数。

static void Main(string[] args)
{
    string[] f;
    bool matched;
    f = GetFileValues();
    matched = IsMatched(f);
    Console.WriteLine(matched);
}

//get the file and place into an array 
static string[] GetFileValues()
{
    var l = new List<string>();
    string path = @"C:\practice-Project-Files\c.csv";
    using (var streamReader = new StreamReader(path))
    {
        using (var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture))
        {
            string s;
            while (csvReader.Read())
            {
                s = csvReader.GetField(0);
                l.Add(s);
            }
        }
    }

    return l.ToArray();
}

//function to accept an array and see if there are all characters 
static bool IsMatched(string[] x)
{
    string first, last;
    Array.Sort(x);
    first = x[0];
    last = x[x.Length - 1];
    if (first == last)
        return true;
    else
        return false;
}

任何帮助将不胜感激。

标签: c#

解决方案


推荐阅读