我想在我的文件夹中生成一个CSV
文件,其数据来自datatable
。我为此编写了以下代码。
public static void CreateCSV(DataTable dt, string FileName)
{
try
{
string strFilePath = ConfigurationSettings.AppSettings["ExcelFilePath"].ToString() + "\\" + FileName;
if (!Directory.Exists(ConfigurationSettings.AppSettings["ExcelFilePath"].ToString()))
Directory.CreateDirectory(ConfigurationSettings.AppSettings["ExcelFilePath"].ToString());
StreamWriter sw = new StreamWriter(strFilePath, false);
DataTable dTemp = dt;
int iColCount = dTemp.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dTemp.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dTemp.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
if (dr[i].ToString().Contains("\n"))
{
string x = dr[i].ToString().Replace("\n", "");
string xc = RemoveSpecialCharacters(x);
string xc1 = RemoveSpecialCharacters1(xc);
//sw.Write(x);
sw.Write(xc1.Replace(", ", ""));
}
else
{
string x = dr[i].ToString().Replace(",", "");
string xc = RemoveSpecialCharacters(x);
string xc1 = RemoveSpecialCharacters1(xc);
sw.Write(xc1.Replace(", ", ""));
}
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
catch (Exception ex)
{
//ErrorLog.Insert(ex.Message, ex.StackTrace, "Program.cs - MailReport", null);
}
}
我在app.config
文件中设置的文件夹路径位于
<add key="ExcelFilePath" value="ExcelData" />
但仍然没有创建csv。我错过了什么,请帮助
答案 0 :(得分:1)
你仍然有一个相对路径而不是绝对路径。你需要一个绝对的。
使用
strFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationSettings.AppSettings["ExcelFilePath"].ToString(), FileName);
和
Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationSettings.AppSettings["ExcelFilePath"].ToString()));
创建目录。无需检查目录是否存在,CreateDirectory只会尝试创建它,如果它不存在。