![](/img/trans.png)
[英]How to read data from a text file/dat file,Dynamically create columns and load the data into a data table using c#
[英]How to read data from text file and store in database table using C#?
#Softdrinks
Cola 2
Sprote 3
Fant 4
Redbull 2
#Pide-Lahmacun
Pide Mozarella 12
Pide Hackfleisch 12
Pide Feta-Hackfleisch 14
Pide Spinat 13
Pide Spinat-Ei 14
以上是文本文件格式。 here # 定義產品的類別名稱。'Cola 2' 定義產品名稱和價格。 其中產品名稱是可樂,價格是 2。現在如何將此數據添加到我的產品表中。我使用的是 c# 和 SQL。 謝謝。
使用以下代碼解析文本文件,然后使用字符串放入數據庫。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication108
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
string line = "";
string category = "";
string pattern = @"(?'name'.*)\s+(?'price'\d+)";
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
if (line.StartsWith("#"))
{
category = line.Substring(1);
}
else
{
Match match = Regex.Match(line, pattern);
string name = match.Groups["name"].Value.Trim();
string price = match.Groups["price"].Value.Trim();
Console.WriteLine("category : '{0}', name : '{1}', price : '{2}'", category, name, price);
}
}
}
Console.ReadLine();
}
}
}
您可以使用類似的方法寫入數據庫。 只需創建您的 SQL 連接。 我建議使用實體框架。 看看實體框架的這個鏈接。 使用實體框架模型插入數據
public int InsertItem(string item1, string item2, string item3)
{
using (var connection = CreateDBConnection())
using (var command = connection.CreateCommand())
{
command.CommandText = @"
INSERT dbo.TableName(item1, item2, item3)
OUTPUT Inserted.Id
VALUES (@item1, @item2, @item3)";
command.Parameters.Add(new SqlParameter("@item1", item1));
command.Parameters.Add(new SqlParameter("@item2", item2));
command.Parameters.Add(new SqlParameter("@item3", item3));
connection.Open();
return (int)command.ExecuteScalar();
}
}
你可以嘗試這樣的事情:
正則表達式的解釋:
1st Capturing Group (.*?)
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\s matches any whitespace character (equal to [\r\n\t\f\v ])
2nd Capturing Group (\d+)
\d+ matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
編碼:
string contents = File.ReadAllText(@"test.txt");
string pattern = @"(.*?)\s(\d+)";
var query = contents.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => Regex.IsMatch(x, pattern))
.Select(x => Regex.Match(x, pattern))
.Select(x => new
{
Name = x.Groups[1].Value,
Value = Convert.ToInt32(x.Groups[2].Value)
});
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
dataTable.Columns.Add(new DataColumn("Value", Type.GetType("System.Int32")));
foreach (var item in query)
{
DataRow dr = dataTable.NewRow();
dr["Name"] = item.Name;
dr["job1"] = item.Value;
dataTable.Rows.Add(dr);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.