RAGHUNATH

RAGHUNATH

  • 1.7k
  • 63
  • 49.5k

c# Pipe seperated file(.psv) Issue with \r\n character

Mar 19 2015 2:12 PM

I had write data table to pipe separated file (|) using below code. the problem is i had a html template in database contains \r\n . due to  \r\n  in data the data is getting line by line in psv file. to overcome that i had tried several ways to resolve it but no luck.. so issue is happening at when ever i had a data containing \r\n ..does any one guess why this issue is happening.




public static void start()
{
string filePath = @"E:\Files\2.psv;
string ConnectionString = "server=localhost;database=sql
sample;Integrated Security=SSPI;";
con.ConnectionString = ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[dbo].[getDetailsCodeId]";
cmd.Parameters.AddWithValue("@id", Id);
con.Open();

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
StringBuilder sb = new StringBuilder();
bool isColumnNameAppend = false;
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate,
FileAccess.ReadWrite);
StreamWriter str = new StreamWriter(fs);
int count = dt.Columns.Count;
str.BaseStream.Seek(0, SeekOrigin.End);

if (!isColumnNameAppend)
{
for (int i = 0; i < count; i++)
{
sb.Append(dt.Columns[i].ColumnName + '|');
}
sb.Append(Environment.NewLine);
isColumnNameAppend = true;
}

for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(PsvQuote((dt.Rows[j][k].ToString())) + '|');
}
sb.Append(Environment.NewLine);
}

str.Write(sb.ToString());
str.Flush();
str.Close();
fs.Close();
}


public static string PsvQuote(string text)
{
text = String.Format("\"{0}\"", text);
return text;
}