遇到个需求,调用第三方Api获取文件并读取文件内容插入到数据库,记录一下:
class Program
{
static void Main(string[] args)
{
#region 下载文件
var url = "Api地址";
var download = new WebClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
string saveDirpath = AppSetting.FilePtah;//设置的地址,例:D:\
string fileName = Guid.NewGuid().ToString();
string saveFilePath = $"{saveDirpath}\\{fileName}.csv";
if (!Directory.Exists(saveDirpath))
{
Directory.CreateDirectory(saveDirpath);
}
download.DownloadFile(url, saveFilePath);
#endregion
#region 读取文件并插入数据库
FileStream fs = new FileStream(saveFilePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
DataTable dt = new DataTable();
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine = null;
string[] tableColumn = null;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
if (IsFirst == true)
{
tableColumn = strLine.Split(',');
IsFirst = false;
}
else
{
aryLine = strLine.Split(',');
SortedList pairs = new SortedList();
for (int i = 0; i < tableColumn.Length; i++)
{
pairs.Add(tableColumn[i], aryLine[i]);
}
DBHelper.Default.Insert("表名", pairs);//插入数据库操作
}
}
sr.Close();
fs.Close();
#endregion
#region 读取完成,删除文件
if (File.Exists(saveFilePath))
{
File.Delete(saveFilePath);
}
#endregion
}
}
public int Insert(string TableName, SortedList Insert_ColumnsNameAndValue)
{
string sql = "INSERT INTO " + TableName;
sql += "(";
for (int i = 0; i < Insert_ColumnsNameAndValue.Count; i++)
{
sql += i > 0 ? "," : "";
sql += Insert_ColumnsNameAndValue.GetKey(i);
}
sql += ")";
sql += " values ";
sql += "(";
for (int i = 0; i < Insert_ColumnsNameAndValue.Count; i++)
{
sql += i > 0 ? "," : "";
sql += "'" + Insert_ColumnsNameAndValue.GetByIndex(i) + "'";
}
sql += ")";
int count = this.ExecuteNonQuery(sql);
return count;
}