开发者

Search line in *.CSV-

开发者 https://www.devze.com 2023-01-16 07:43 出处:网络
I can\'t belive, the easiest task won\'t work! I just want to loop through a csv file by using the StreamReader-Class and find a key in a associative line.

I can't belive, the easiest task won't work!

I just want to loop through a csv file by using the StreamReader-Class and find a key in a associative line. e.g.:

  1. key1;value1
  2. key2;value2
  3. key3;value3

If the key exists, no problems. Otherwise EOF should be reached, but it does not work!

If I discard the buffered data, EOF will be reached everytime. In result no key will be found.

Edit: with all the suggestions, but same result!

StreamReader reader = null;
if(!string.IsNullOrEmpty(textBox1.Text))
{
    try
    {
        reader = new StreamReader(@"ident.csv", Encoding.ASCII);
        string b开发者_运维知识库uffer;
        string[] str = null;

        while((buffer = reader.ReadLine()) != null)
        {
            if(buffer.Contains(";"))
            {
                str = buffer.Split(';');
                if(str[0].Equals(textBox1.Text))
                    break;
            }
        }

        if(reader == null)
        {
            MessageBox.Show("Ident not found!");
            textBox2.Text = "";
        }
        else
        {
            textBox2.Text = str[1];
            Clipboard.SetText(str[1]);
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        reader.Dispose();
        reader.Close();
    }
}
else
{
    MessageBox.Show("Set ident!");
}
}


very strange, this works on my pc:

static void Main(string[] args)
{
    string buffer = string.Empty;
    StreamReader reader = new StreamReader(@"e:\a.csv");
    do
    {
        buffer = reader.ReadLine();
        if (buffer.Contains(";"))
        {

            string[] str = buffer.Split(';');
            if (str[0] == "1")
            {
                Console.WriteLine("ok");
                break;
            }
        }
    }
    while (!reader.EndOfStream);
}

csv contains:

1;2;3;4;5;
sdfsdf;sdfsdfcv;aasd;


As Konerak points out in his comment, use .equals() to compare Strings. It just happens that "1" == "1" AND "1".equals("1") both are true but it's just a coincidence (that's why the second piece of code works). More on String equality here.


Do not forget:the file coding is the key for read files! coding:UTF8,ASCII,UTF16,GB2312


Stupid thought but does either ident.csv or your textbox contain any extra spaces?

Try something like if(str[0].Trim().Equals(textBox1.Text.Trim()))

0

精彩评论

暂无评论...
验证码 换一张
取 消