using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SanJuSFTP
{
public class Common
{
public static DataTable CsvToDt(string path)
{
OleDbConnection OleCon = new OleDbConnection();
try
{
DataSet dsCsvData = new DataSet();
OleDbCommand OleCmd = new OleDbCommand();
OleDbDataAdapter OleDa = new OleDbDataAdapter();
OleCon.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path.Substring(0, path.LastIndexOf("\")) + ";Extended Properties='Text;FMT=Delimited(,);HDR=YES;IMEX=1';";
OleCon.Open();
OleCmd.Connection = OleCon;
OleCmd.CommandText = "select * from [" + path.Substring(path.LastIndexOf("\") + 1) + "] where 1=1";
OleDa.SelectCommand = OleCmd;
OleDa.Fill(dsCsvData, "Csv");
return dsCsvData.Tables[0];
}
catch (Exception ex)
{
LogHelper.WriteLog(ex.Message);
return null;
}
finally
{
OleCon.Close();
}
}
/// <summary>
/// datatable转csv
/// </summary>
/// <param name="dt"></param>
/// <param name="fileName"></param>
public static void DtToCsv(DataTable dt, string fileName)
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
try
{
string data = "";
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
data += "" + dt.Rows[i][j].ToString();
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
}
catch (Exception ex)
{
}
finally
{
sw.Close();
fs.Close();
}
}
/// <summary>
/// 新文件名
/// </summary>
/// <param name="oldFilePath">文件路径</param>
/// <param name="oldFileName">文件名称</param>
/// <returns></returns>
public static string GetNewFilePath(string oldFilePath, string oldFileName)
{
string newFilePath = oldFilePath + oldFileName.Substring(0, oldFileName.IndexOf("."))
+ DateTime.UtcNow.ToString("yyyyMMdd") +
oldFileName.Substring(oldFileName.IndexOf("."));
return newFilePath;
}
/// <summary>
/// 修改本地文件名
/// </summary>
/// <param name="oldStr">旧文件名</param>
/// <param name="newStr">新文件名</param>
public static void Rename_Local(string oldStr, string newStr)
{
// 改名方法
FileInfo fi = new FileInfo(oldStr);
FileInfo fi_new = new FileInfo(newStr);
if (fi_new.Exists)
{
fi_new.Delete();
}
fi.MoveTo(Path.Combine(newStr));
}
}
}