1)我正在尝试阅读文本文件,但它显示错误,如
foreach语句不能对'System.IO.StreamReader'类型的变量进行操作,因为'System.IO.StreamReader'不能 包含'GetEnumerator'的公共定义
这是我的 C#代码......
using (StreamReader sr = new StreamReader(@"D:\test1.txt"))
{
while (sr.Peek() >= 0)
{
//contents of foreach loop go here
foreach (var line in sr)
{
var items = line.Split(new[] { '\t', '\n' }).ToArray();
if (items.Length != 3)
continue;
var Name = items[0].ToString();
var Email = items[1].ToString();
var Pwd = items[2].ToString();
cmd.CommandText = "insert into Employees values('" + Name + "','" + Email + "','" + Pwd + "')";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
答案 0 :(得分:1)
这对此有用。而不是ForEach
循环,使用while
循环
using (StreamReader sr = new StreamReader(@"D:\test1.txt"))
{
while (sr.Peek() >= 0)
{
//contents of foreach loop go here
while ((line = sr.ReadLine()) != null)
{
var items = line.Split(new[] { '\t', '\n' }).ToArray();
if (items.Length != 3)
continue;
var Name = items[0].ToString();
var Email = items[1].ToString();
var Pwd = items[2].ToString();
cmd.CommandText = "insert into Employees values('" + Name + "','" + Email + "','" + Pwd + "')";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
答案 1 :(得分:1)
错误很清楚。
您只能通过foreach
对实现GetEnumerator
方法的元素进行迭代,而StreamReader
则不会。
StreamReader
有很多优秀而且很好的例子,只需查看一下。
答案 2 :(得分:1)
基本上,Alex.K评论说:
using (StreamReader sr = new StreamReader(@"D:\test1.txt"))
{
while (sr.Peek() >= 0)
{
var line = sr.ReadLine();
var items = line.Split(new[] { '\t', '\n' }).ToArray();
if (items.Length != 3)
continue;
var Name = items[0].ToString();
var Email = items[1].ToString();
var Pwd = items[2].ToString();
cmd.CommandText = "insert into Employees values('" + Name + "','" + Email + "','" + Pwd + "')";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
你在窥视检查循环中不需要foreach
,只需读一行。
这是MSDN的典型用法,它非常清楚如何读取行:
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
要避免使用SQL injection vulnerability
,请使用Parameters
处理参数:
// this is baaaaad
cmd.CommandText = "insert into Employees values('" + Name + "','" + Email + "','" + Pwd + "')";
// will become
cmd.CommandText = "insert into Employees values(@Name, @Email, @Pwd)";
cmd.Parameters["@Name"].Value = Name;
cmd.Parameters["@Email"].Value = Email;
cmd.Parameters["@Pwd"].Value = Pwd;
// somewhere before, where you create command
cmd.Parameters.Add("@Name", type);
cmd.Parameters.Add("@Email", type);
cmd.Parameters.Add("@Pwd", type);
答案 3 :(得分:0)
你可以在这种类型中使用
foreach (var line in File.ReadLines(@"D:\test1.txt"))
{
}