Reading a text file with Tabs

1k views Asked by At

In a text file I use TAB to create a column-like grid, but apparently those tabs are just read as spaces, which of course breaks the formatting.

This is my code (path is the file path, e.g. D:/folder/testtt.txt):

if (File.Exists(path))
{
    using (TextReader tr = new StreamReader(path))
    {
        while (tr.Peek() != -1)
        {
            Response.Write(tr.ReadLine() + "<br/>");
        }
    }
}

This is how it should appear:

Screenshot

Link

And this is how it currently appears:

Screenshot

Link

How can I fix that?

3

There are 3 answers

0
alisabzevari On BEST ANSWER

There's no tab entity defined in ISO-8859-1 HTML, so I think you can replace tab characters with some &nbsp; characters:

if (File.Exists(path))
{
    using (TextReader tr = new StreamReader(path))
    {
        while (tr.Peek() != -1)
        {
            var htmlLine = tr.ReadLine().Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;") + "<br/>";
            Response.Write(htmlLine);
        }
    }
}
1
AudioBubble On

Why don't you output the file contents in a <pre> tag? It will preserve the tabs and give you a nice monospaced output.

1
d.popov On

You can create real grid, as you are outputting HTML:

if (File.Exists(path))
{
    using (TextReader tr = new StreamReader(path))
    { 
        Response.Write("<table>");
        while (tr.Peek() != -1)
        {
            Response.Write("<tr><td>");
            Response.Write(String.Join("</td><td>", tr.ReadLine().Split('/t')));
            Response.Write("</td></tr>");
        }
        Response.Write("</table>");
    }
}

This will be the cleanest solution for me - you want it to look like a grid - make a grid :)