从文本文件中提取数据

时间:2015-01-20 18:44:40

标签: c#

我试图从.txt文件中提取数据并将其放入数据库中。数据是冒号旁边的数字。我尝试过File.ReadAllLines函数,但有些行有相同的单词。以下是文本文件的一部分:

X质心偏移:0.1233 mm

Y质心偏移:-0.00053871 mm

偏心(梁):0.10004

偏心(阴影):0.118

这是我的代码的开头。我试图将这些值作为我定义的变量放入数据库中。

private void btn_import_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        string Date;
        float A_X_Off;
        float A_Y_Off;
        float A_EccBeam;
        float A_EccSha;

        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.15.0;
        Data Source = C:\\Users\\Kevin\\Desktop\\Accuray Project\\CkAppDatabase.accdb";


        // CODE to pull out text file values and make the output a variable.                    

        OleDbCommand cmd = new OleDbCommand("INSERT into CK_QA_App(Date, A_X_Off, A_Y_Off, A_EccBeam, A_EccSha) VALUES(@Date, @A_X_Off, @A_Y_Off, @A_EccBeam, @EccSha)");

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {                         

        }

2 个答案:

答案 0 :(得分:0)

使用File.ReadAllLines后,您可以对结果使用for循环。

在循环内部使用带方法的开头和一些ifs将行匹配到正确的变量以分配给它。

使用分割功能使用冒号分割以获取值。请记住在值上调用trim以删除前导空格。

答案 1 :(得分:0)

假设您正在阅读文件f

string[] inputs = File.ReadAllLines(f);

foreach (String line in inputs) {

string data = Regex.Match(line, @"-?\d+(?:\.\d+)?").Value;
//This will extract any decimal in each line as a string
//you can then parse it to double/float or any type you want and store it in your database

}