我的路径中有两个文本文件,知道为什么只有一个文本文件插入到我的数据库中?
运行应用程序后,它会停止并返回一个 ' System.NullReferenceException'
附加信息:对象引用未设置为的实例 对象
这是代码。
try
{
var files = from file in Directory.EnumerateFiles(@"C:\Users\K\Desktop\New folder", "*.txt", SearchOption.AllDirectories)
from line in File.ReadLines(file)
select new
{
File = file,
Line = line
};
foreach (var f in files)
{
Console.WriteLine("{0}\t{1}", f.File, f.Line);
using (StreamReader sr = new StreamReader(f.File))
{
foreach (string line in File.ReadAllLines(f.File).SkipWhile(x => !x.Contains("[Start]")))
{
string readLine;
do
{
readLine = sr.ReadLine();
string[] readLineSplit = readLine.Split('|');
if(readLineSplit.Length > 1)
{
using (MySqlConnection con = new MySqlConnection(@"server=localhost;database=test;uid=root;pwd=pw;"))
{
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Products(Product_Name, Product_Price, QTY) VALUES (@Product_Name, @Product_Price, @QTY)", con);
cmd.Parameters.AddWithValue("@Product_Name", readLineSplit[0].ToString());
cmd.Parameters.AddWithValue("@Product_Price", readLineSplit[1].ToString());
cmd.Parameters.AddWithValue("@QTY", readLineSplit[2]);
cmd.ExecuteNonQuery();
}
}
} while (!sr.EndOfStream);
}
答案 0 :(得分:0)
应该是这样的:不测试'因为这里没有mysql而且时间更少:
var files = Directory.EnumerateFiles(@"C:\Users\K\Desktop\New folder", "*.txt", SearchOption.AllDirectories);
using (MySqlConnection con = new MySqlConnection(@"server=localhost;database=test;uid=root;pwd=pw;"))
{
con.Open(); // new Position of con.Open()
foreach (var f in files)
{
Console.WriteLine(f);
string[] Lines = File.ReadAllLines(f);
bool processRecord = false;
foreach (string line in Lines)
{
if (!processRecord)
{
if (Lines.Contains("[Start]"))
{
processRecord = true;
continue;
}
}
if (Lines.Contains("[End]"))
{
processRecord = false;
continue;
}
if (processRecord)
{
string[] readLineSplit = line.Split('|');
if (readLineSplit.Length > 1)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO Products(Product_Name, Product_Price, QTY) VALUES (@Product_Name, @Product_Price, @QTY)", con);
cmd.Parameters.AddWithValue("@Product_Name", readLineSplit[0]);
cmd.Parameters.AddWithValue("@Product_Price", readLineSplit[1]);
cmd.Parameters.AddWithValue("@QTY", readLineSplit[2]);
cmd.ExecuteNonQuery();
}
}
}
}
}
编辑:抱歉,犯了错误......现在完成了。
编辑:现在完成!
编辑: [结束]条件已添加。
编辑:移动con.Open()只需调用一次。
编辑:更改了小错误并删除了错误的文件枚举