C#读取写入文本文件,一个文本文件存放路径:d:\config.txt 读取config.txt第三行内容,该行内容为数值,如:10;SQL数据库中有record表,表中有个ID字段,为主键,增加一行ID会自动加1
问题:1、读取config.txt第三行内容。读取record表中ID字段值大于第三行内容的数据。并将数据存入另外一张表如:A表。同时将最后一行ID字段值写入并覆盖config.txt第三行内容。
2、record表会不断扩大。每隔30S,C#程序循环执行上述操作。
请教,谢谢!
【以下回答由 GPT 生成】
using System;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
class Program
{
private const string connectionString = "Your_Connection_String"; // 替换为你的数据库连接字符串
private const string configFilePath = "d:\\config.txt";
private const int intervalInSeconds = 30;
static void Main(string[] args)
{
Timer timer = new Timer(ExecuteTask, null, TimeSpan.Zero, TimeSpan.FromSeconds(intervalInSeconds));
Console.WriteLine("Press any key to stop the program...");
Console.ReadKey();
timer.Dispose();
}
private static void ExecuteTask(object state)
{
try
{
int configValue = GetConfigValue();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = $"SELECT * FROM record WHERE ID > {configValue}";
using (SqlCommand command = new SqlCommand(query, connection))
{
SqlDataReader reader = command.ExecuteReader();
using (StreamWriter writer = File.CreateText("A_table.txt"))
{
while (reader.Read())
{
string rowData = $"{reader["ID"]}\t{reader["Column1"]}\t{reader["Column2"]}\t..."; // 替换为你的表结构
writer.WriteLine(rowData);
}
}
}
int lastID = GetLastID();
UpdateConfigValue(lastID);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
private static int GetConfigValue()
{
string line = File.ReadLines(configFilePath).Skip(2).FirstOrDefault();
if (!string.IsNullOrEmpty(line))
{
int value;
if (int.TryParse(line, out value))
{
return value;
}
}
throw new Exception("Invalid config file format");
}
private static int GetLastID()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT TOP 1 ID FROM record ORDER BY ID DESC";
using (SqlCommand command = new SqlCommand(query, connection))
{
return (int)command.ExecuteScalar();
}
}
}
private static void UpdateConfigValue(int value)
{
string[] lines = File.ReadAllLines(configFilePath);
lines[2] = value.ToString();
File.WriteAllLines(configFilePath, lines);
}
}
说明:
1. 创建一个Timer
,设置其ExecuteTask
方法每30秒执行一次。 2. 在ExecuteTask
方法中,首先读取配置文件的第三行内容,将其转换为数值。 3. 使用给定的连接字符串建立与SQL数据库的连接。 4. 构建SQL查询语句,选取record表中ID大于配置文件第三行内容的数据。 5. 执行查询并将结果写入A表的文本文件。 6. 获取record表中最后一行的ID字段值。 7. 更新配置文件的第三行内容为最后一行的ID值。 8. 实现过程中,如果出现任何错误,将错误信息输出到控制台。
请注意替换Your_Connection_String
为你的数据库连接字符串,并根据你自己的表结构进行修改。
用 string[] lines = File.ReadAllLines("config.txt");
将文本文件按行读取到数组,然后下面是你的逻辑,可以用linq查询