AnimaSola
AnimaSola

Reputation: 7846

Write Tab Delimited File

I'm having trouble writing a Tab-delimited File and I've checked around here and have not gotten my answers yet.

So I've got a function that returns the string with the important pieces below (delimiter used and how I build each line):

var delimiter = @"\t";
sb.Append(string.Join(delimiter, itemContent));
sb.Append(Environment.NewLine);

The string returned is like this:

H\t13\t170000000000001\t20150630
D\t1050\t10.0000\tY
D\t1050\t5.0000\tN

And then I write it to a file with this (content below is the string above):

var content = BuildFile(item);
var filePath = tempDirectory + fileName;

// Create the File
using (FileStream fs = File.Create(filePath))
{
    Byte[] info = new UTF8Encoding(true).GetBytes(content);
    fs.Write(info, 0, info.Length);
}

However, the file output is this with no tabs (opened in notepad++):

H\t13\t170000000000005\t20150630
D\t1050\t20.0000\tN
D\t1050\t2.5000\tY

When it should be more like this (sample file provided):

H   100115980   300010000000003 20150625
D   430181  1   N
D   342130  2   N
D   459961  1   N

Could this be caused by the encoding I used? Appreciate any input you may have, thanks!

Upvotes: 6

Views: 41577

Answers (2)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131334

There is a typo in your code. The @ prefix means that the following string is a literal so @"\t" is a two-character string with the characters \ and t

You should use "\t" without the prefix.

You should consider using a StreamWriter instead of constructing the entire string in memory and writing the raw bytes though. StreamWriter uses UTF-8 by default and allows you to write formatted lines just as you would with Console.WriteLine:

var delimiter ="\t";

using(var writer=new StreamWriter(filePath))
{
    var line=string.Join(delimiter, itemContent);
    writer.WriteLine(line);
}

Upvotes: 10

Hans Kesting
Hans Kesting

Reputation: 39284

Using var delimiter = @"\t";, the variable contains a literal \ plus t. The @ syntax disables the backslash as "special". In this case you really want

var delimiter = "\t";

to have a tab character.

Upvotes: 17

Related Questions