[英]CSV is not getting generated in the folder for console application
I want to generate a CSV
file in my folder with the data coming from datatable
. 我想在我的文件夹中生成一个
CSV
文件,其中的数据来自datatable
。 I have written the below code for that. 我为此编写了以下代码。
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);
}
}
And the folder path which I have set in app.config
file is below 我在
app.config
文件中设置的文件夹路径如下
<add key="ExcelFilePath" value="ExcelData" />
but still the csv is not getting created. 但仍然没有创建csv。 Am I missing something, kindly help
我错过了什么吗,请帮忙
You still have a relative path not an absolute one. 您仍然拥有相对路径,而不是绝对路径。 You need an absolute one.
您需要一个绝对的。
Use 采用
strFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationSettings.AppSettings["ExcelFilePath"].ToString(), FileName);
and 和
Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationSettings.AppSettings["ExcelFilePath"].ToString()));
to create the directory. 创建目录。 No need to check if directory exists, CreateDirectory will only try to create it if it does not exist.
无需检查目录是否存在,如果目录不存在,CreateDirectory只会尝试创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.