1)我有一个像这样的文本文件。
Sanjay sn.mehta@gmail.com 123 Ajay ap123@yahoo.com 456 Vijay vijymalya@gmail.com 789 Sujay spnakum@tahoo.com 141 Jay jaybhalara@yahoo.com 275 Dhananjay dh@gmail.com 786
2)下面的我的代码非常适合读取此文本文件并将数据插入数据库。 这是我的代码。我正在使用 C#
//Reading all lines of Text file
string[] alllines = File.ReadAllLines(@"D:\test1.txt");
for (int i = 1; i < alllines.Length; i++)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
//each word in line will be store in array when tab dilimiter arrive
string[] items = alllines[i].Split(new char[] { '\t','\n' }).ToArray<string>();
string Name = items[0].ToString();
string Email = items[1].ToString();
string Pwd = items[2].ToString();
//insert each word into database
cmd.CommandText = "insert into Employees values('" + Name + "','" + Email +"','" + Pwd + "')";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
conn.Dispose();
Label1.Visible = true;
Label1.Text = "Data Successfully Inserted into Database.";
}
3)但是当文件类似......时,我的代码无法读取文本文件。
Sanjay sn.mehta@gmail.com 123 Ajay ap123@yahoo.com 456 Vijay vijymalya@gmail.com 789 ------------------------------------------ Sujay spnakum@tahoo.com 141 Jay jaybhalara@yahoo.com 275 Dhananjay dh@gmail.com 786
4)我想要的只是当那种无格式的线到达时它应该忽略它并处理下一行。或者每当定界符到达时它开始处理
5)您可以使用StreamReader并逐行读取文件。
答案 0 :(得分:0)
if(items.Length != 3)
会告诉您分割是否正确。
我所做的一些改变是:
这是代码。
//Reading all lines of Text file
var allLines = File.ReadAllLines(@"D:\test1.txt");
var connectionString = @"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = connection.CreateCommand();
foreach (var line in allLines)
{
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();
}
Label1.Visible = true;
Label1.Text = "Data Successfully Inserted into Database.";
}
此外,您的SQL中的Using parameters更安全。在编写本文时,您很容易受到SQL注入攻击。
编辑:
要使用流式读取器,它将如下所示:
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
//contents of foreach loop go here
}
}