C# c中列值的转义字符#
以下代码从sqlserver2016表读取数据并将其转储到本地文件夹。但某些列值包含逗号,它将值替换为另一列作为分隔符我使用了逗号,因此如何在值中保留逗号而不将值替换为另一列。我的代码示例如下。任何帮助都将不胜感激C# c中列值的转义字符#,c#,C#,以下代码从sqlserver2016表读取数据并将其转储到本地文件夹。但某些列值包含逗号,它将值替换为另一列作为分隔符我使用了逗号,因此如何在值中保留逗号而不将值替换为另一列。我的代码示例如下。任何帮助都将不胜感激 SqlConnection myADONETConnection = new SqlConnection(); myADONETConnection = (SqlConnection)(Dts.Connections["db_connection"].AcquireConnectio
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["db_connection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Read data from table or view to data table
string query = SQLQuery;
SqlCommand cmd = new SqlCommand(query, myADONETConnection);
//myADONETConnection.Open();
DataTable d_table = new DataTable();
d_table.Load(cmd.ExecuteReader());
myADONETConnection.Close();
string FileFullPath = DestinationFolder + "\\" + FileNamePart + "_" + datetime + FileExtension;
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(d_table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
Dts.TaskResult = (int)ScriptResults.Success;
SqlConnection myADONETConnection=newsqlconnection();
myADONETConnection=(SqlConnection)(Dts.Connections[“db_connection”].AcquireConnection(Dts.Transaction)作为SqlConnection);
//从表或视图读取数据到数据表
字符串查询=SQLQuery;
SqlCommand cmd=新的SqlCommand(查询,myADONETConnection);
//myADONETConnection.Open();
DataTable d_table=新DataTable();
d_table.Load(cmd.ExecuteReader());
myADONETConnection.Close();
字符串FileFullPath=DestinationFolder+“\\”+FileNamePart+“\\”+datetime+FileExtension;
StreamWriter sw=null;
sw=新StreamWriter(FileFullPath,false);
//将标题行写入文件
int ColumnCount=d_table.Columns.Count;
对于(int ic=0;ic
将所有值用引号括起来。这将跳过逗号,无论您稍后使用什么方法解析文件,都应该理解它
是csv中转义的默认方式
下面应该可以做到这一点。这确实假设您的数据不包含任何引号
sw.Write('"');
sw.Write(dr[ir].ToString());
sw.Write('"');
如果您的数据确实包含引号,则需要将其加倍,如下图所示,以便转义引号
value1 | value2 | super"special"value
"value1","value2","super""special""value"
用引号将所有值括起来。这将跳过逗号,以后解析文件时使用的任何方法都应该理解它 是csv中转义的默认方式 下面的内容应该可以做到这一点。这并不假设您的数据不包含任何引号
sw.Write('"');
sw.Write(dr[ir].ToString());
sw.Write('"');
如果您的数据确实包含引号,则需要将其加倍,如下图所示,以便转义引号
value1 | value2 | super"special"value
"value1","value2","super""special""value"
“置换”是什么意思?您能给出您得到的输出和想要得到的输出吗?数据库示例中的值,列名:Data和value:“this is,sample”。但当我将其写入csv文件时,值分为两列,分别为“this is”和“sample”,我希望整个值“this is,sample”应该在csv的一列中,如果其中有值,您不使用双引号吗?置换是什么意思?您能给出您得到的输出和想要得到的输出吗?数据库示例中的值,列名:Data和value:“this is,sample”。但当我将其写入csv文件时,值分为两列,分别为“this is”和“sample”,我希望整个值“this is,sample”应该在csv的一列中,如果它的值有,如果它包含任何引号或其他字符,我如何处理它如果它包含任何引号或其他字符,我如何处理它