Search code examples
text-filesblazor-server-sidetext-indent

Im my Blazor Server side app I read a text file line by line. But When when I visualise the lines in my razor page the line indents are not shown.Why?


Im my Blazor Server side app's razor.cs I read an error log text file line by line. In the log file there are .NET exceptions that are written with line indents for better overview. But When when I visualise the log file contents in my razor page the line indents are not shown, why? What can I do to show the lines with their original line indents?

Log text File Content My razor.cs page

 public List<string> Error_log = new List<string>() { };
 public void Read_Logfile
 {
   Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
   var lines = File.ReadLines(CommonClass.error_path, Encoding.GetEncoding("Windows-1254"));
   var line_trimmed = "";

   foreach (var line in lines)
   {
     TagService.Error_log.Add(line);
   }
 }

My razor page

<table>
    @for (int f = 0; f < TagService.Error_log.Count; f++)
    {
        <tr>
            <td class="sys_config_file">@TagService.Error_log[f]</td>
        </tr>
    }
</table>

Solution

  • The issue you're facing with the line indents not being shown in your Razor page could be related to HTML rendering and whitespace handling. By default, HTML collapses consecutive whitespace characters into a single space.

    To preserve the line indents from your text file in the rendered HTML, you can use the <pre> tag or apply CSS styles to preserve whitespace. Here's an example of how you can modify your Razor page to preserve line indents:

    <style>
        .preformatted {
            white-space: pre;
        }
    </style>
    
    <table>
        @for (int f = 0; f < TagService.Error_log.Count; f++)
        {
            <tr>
                <td class="sys_config_file"><pre class="preformatted">@TagService.Error_log[f]</pre></td>
            </tr>
        }
    </table>
    

    In this example, we added a CSS class called .preformatted and applied it to the <pre> tag inside the <td> element. The white-space: pre; CSS property preserves the line indents and other whitespace characters as they are in the original text.

    Alternatively, you can use the <pre> tag directly without CSS styling:

    <table>
        @for (int f = 0; f < TagService.Error_log.Count; f++)
        {
            <tr>
                <td class="sys_config_file"><pre>@TagService.Error_log[f]</pre></td>
            </tr>
        }
    </table>
    

    By using the <pre> tag, the line indents and whitespace characters will be preserved as-is in the rendered HTML output, maintaining the original formatting from your text file.