第一步已经完成了,卡在了红字上。文件一行四列,如果解析成功将数据添加到对应SQL表,并把文件转移到指定的OK文件夹。希望路过的大神可以指教,还有后面的文件转移。不知道图片说明能不能表达清楚,先感谢大神啦
问题分两个部分,解析CSV和转移文件。
解析CSV可以直接在网上找现成的代码,不用手写。
一般来说解析成功会返回数据集,解析失败会返回空或者抛出异常,针对结果进行下一步操作就可以了。
转移文件,针对你的需求封装一个函数
private static string GetNewPath(string filepath, string newDirName)
{
string filename = Path.GetFileName(filepath);
string dirName = Path.GetDirectoryName(filepath);
return Path.Join(dirName, @$"{newDirName}\{filename}");
}
调用
// 假设filepath变量是你当前解析的文件路径
// 解析成功时
File.Move(filepath, GetNewPath(filepath, "OK"));
// 解析失败时
File.Move(filepath, GetNewPath(filepath, "NG"));
private void GetDataTabletFromCSVFile(string fileName)
{
DataTable dt = new DataTable();
//dt.TableName = fileName;
try
{
using (TextFieldParser csvReader = new TextFieldParser(fileName))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
//foreach (string column in colFields)
//{
// DataColumn datecolumn = new DataColumn(column);
// datecolumn.AllowDBNull = true;
// dt.Columns.Add(datecolumn);
//}
dt.Columns.AddRange(new DataColumn[8] {
new DataColumn("Symbol", typeof(string)),
new DataColumn("ISIN", typeof(string)),
new DataColumn("Company", typeof(string)),
new DataColumn("FirstListingDate", typeof(string)),
new DataColumn("FaceValue", typeof(string)),
new DataColumn("PaidUpValue", typeof(string)),
new DataColumn("MarketLot",typeof(string)),
new DataColumn("industry",typeof(string))
});
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
dt.Rows.Add(fieldData);
}
var builder = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
string DBconnection = configuration.GetSection("ConnectionString").Value;
using (SqlConnection dbConnection = new SqlConnection(DBconnection))
{
dbConnection.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = "Static.dbo.Securitiesinfo";
foreach (var column in dt.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(dt);
}
}
}
}
catch (Exception ex)
{
var x = ex;
}
}
大神可以看一下,这个可以拿过来用吗