*.CSV- 中的搜索行
我不敢相信,最简单的任务也行不通!
我只想使用 StreamReader-Class 循环遍历 csv 文件并在关联行中找到一个键。 例如:
- key1;value1
- key2;value2
- key3;value3
如果 key 存在,则没有问题。否则应该达到EOF,但是不起作用!
如果我丢弃缓冲的数据,每次都会达到EOF。结果找不到密钥。
编辑:包含所有建议,但结果相同!
StreamReader reader = null;
if(!string.IsNullOrEmpty(textBox1.Text))
{
try
{
reader = new StreamReader(@"ident.csv", Encoding.ASCII);
string buffer;
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!");
}
}
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.:
- key1;value1
- key2;value2
- 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 buffer;
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!");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
很奇怪,这适用于我的电脑:
csv 包含:
very strange, this works on my pc:
csv contains:
正如 Konerak 在他的评论中指出的那样,使用 .equals() 来比较字符串。
碰巧 "1" == "1" AND "1".equals("1") 都是 true,但这只是一个巧合(这就是第二段代码有效的原因)。有关字符串相等性的更多信息请参见此处。
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.
不要忘记:文件编码是读取文件的关键!
编码:UTF8、ASCII、UTF16、GB2312
Do not forget:the file coding is the key for read files!
coding:UTF8,ASCII,UTF16,GB2312
愚蠢的想法,但 ident.csv 或您的文本框是否包含任何额外的空格?
尝试类似
if(str[0].Trim().Equals(textBox1.Text.Trim()))
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()))