繁体   English   中英

如何读取txt文件并将其导入到sql数据库?

[英]How can i read txt file and import it to sql database?

我有.txt文件,我想阅读文档并将其存储到db。

这是我的txt文件:

0 79 142
1 202 135
4 122 125
5 152 123
6 110 122
7 165 121
8 100 124
9 176 121
11 138 159
12 121 155
13 154 154
17 139 181
19 119 182
20 160 179
22 141 221

我想读取第一个整数,即0,然后是79、142。 之后,我将存储79-> 0-X和142-> 0-Y

然后202-> 1-X和135-> 1-Y,这样将继续。

我试过memoryStream,但它读为字符串。而且我对C#也不太满意。

这是我尝试的..

            int counter = 0;
            string line;


            System.IO.StreamReader file =
                new System.IO.StreamReader(@"C:\Users\musa\Desktop\test\00002fa001d_931230_AP.txt");
            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine(line);
                counter++;
            }

            file.Close();

            MessageBox.Show(Convert.ToString(counter));

因此,新问题是如何解析行?

只需将其读取为字符串,然后使用.Split('')即可将字符串拆分为单独字符串的数组。 您可以将它们转换为整数。

您是否考虑过使用StreamReader?

using (StreamReader sr = new StreamReader(path)) 
{
    while (sr.Peek() >= 0) 
    {
        Match match = Regex.Match(sr.ReadLine(), @"^(?<Index>\d+)\s(?<X>\d+)\s(?<Y>\d+)$");
        // You can now access the Index, X and Y by using the following statement
        // match.Groups["Index"];
        // match.Groups["X"];
        // match.Groups["Y"];
    }
}

您可以使用int.Parse将字符串解析为int

var coords=File.ReadAllText(path)
               .Split(new char[]{'\r',\n'},StringSplitOptions.RemoveEmptyEntries)
               .Select(i=>
                            new
                            {
                                 X=int.Parse(i.Split(' ')[1]),
                                 Y=int.Parse(i.Split(' ')[2])
                            }
                      );

您现在可以遍历坐标

foreach(var coordinate in coords)
{
    coordinate.X;
    coordinate.Y;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM