1

我正在读取一个文本文件并将其存储到数据库中。单击一下,我就可以从文本文件中读取一行,并将其存储到数据库中。

但是我的文本文件很大,所以我需要一种方法,以便单击即可开始读取文件,并且可以将其存储到数据库中直到文件结束。

这是我的代码:

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();
}
4

2 回答 2

1

You can use as follows

 string text = System.IO.File.ReadAllText(@pathNames);

or

    // 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);
于 2013-10-30T05:42:02.643 回答
0
using (TextReader reader = File.OpenText(@"your file path"))
    {
        string line = reader.ReadToEnd();
        Console.WriteLine(line);
    }

Reader Class, ReadToEnd Method

Reader Class

File.OpenText Method

于 2013-10-30T05:40:25.407 回答