我正在读取文本文件并将其存储到数据库中。只需单击一下,我就可以从文本文件中读取一行,并将其存储到数据库中。
但我的文本文件很大,所以我需要一个方法,这样一次点击就会开始读取文件,并且可以存储到数据库直到文件结尾。
这是我的代码:
Program problem = new Program();
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Billing;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
string line = "";
string billno = null;
string billdate = null;
string hosp_no = null;
string ip_no = null;
string name = null;
string test = null;
string ward = null;
string rad = null;
string pathNames = "C:\\Users\\Administrator\\Desktop\\Ex_1\\KHL.txt";
ArrayList rawData = new ArrayList();
try
{
StreamReader readFile = new StreamReader(pathNames);
do
{
//tim
if ((line = readFile.ReadLine()) != null)
{
// Console.WriteLine(line);
if (line.Contains("RADIOLOGY"))
{
rawData.Add(line);
//Console.ReadKey();
}
}
else
{
line = null;
}
} while (line != null);
int rIn = rawData.Count;
for (int i = 0; i < rIn; i++)
{
con.Open();
string[] data = (rawData[i] + "").Split('~');
string da = "";
hosp_no = data[1].Substring(data[1].Length - 8, 8);
ip_no = data[2].Substring(data[1].Length - 7, 7);
name = data[8].Replace("'", "''");
billno = data[3];
billdate = data[4].Substring(5, 2) + "/" + data[4].Substring(8, 2) + "/" + data[4].Substring(0, 4);
test = data[5];
ward = data[16];
if (data.Length == 1 && data[0] == "") da = "Finish";
else
{
cmd = new SqlCommand("insert into ex_1 values('" + hosp_no + "','" + ip_no + "','" + name.Replace(" ' ", " '' ") + "','" + billno + "','" + billdate + "','" + ward + "','" + test + "')", con);
cmd.Parameters.AddWithValue("@name", name);
cmd.ExecuteNonQuery();
con.Close();
Console.Read();
}
//Console.WriteLine(da);
Console.Read();
}
}
catch (Exception f)
{
Console.WriteLine(f.Message);
Console.Read();
}
答案 0 :(得分:1)
您可以按照以下方式使用
string text = System.IO.File.ReadAllText(@pathNames);
或
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(@pathNames);
答案 1 :(得分:0)
using (TextReader reader = File.OpenText(@"your file path"))
{
string line = reader.ReadToEnd();
Console.WriteLine(line);
}