0

I'm trying to read a csv file so that I can load a jQuery DataTable. The csv file might have different headers. I was using the header to create the columns for the jQuery table. Then loading the file in and creating the rows. I was doing this directly from the csv file and all worked okay, but only if the file was small. I needed to move to using Json in order to implement a way using Linq to sort, filter, and query in the Model portion of the code. While trying to move to an MVC model, I got into a position where I can't extract the rows from the Json data.

Here is the ViewFile, which currently has the LoadDataAsJson (which should be in the Model class, I'll bet). The Json it creates is correct.

   public IActionResult ViewFile()
    {
        string fileName = Request.Form["fileName"];
        ViewData["name"] = fileName;
        ViewData["data"] = LoadDataAsJson(dir + Path.DirectorySeparatorChar + fileName, 100);
        return View();
    }

    private string LoadDataAsJson(string fileName, int limit)
    {
        string[] headers = new string[8];
        StringBuilder bldr = new StringBuilder();
        bldr.Append("[");
        using (TextReader reader = new StreamReader(fileName))
        {
            String line = null;
            int k = 0;
            while ((line = reader.ReadLine()) != null)
            {
                if (k > limit)
                    break;
                if (k++ != 0)
                {
                    if (k != 2)
                        bldr.Append(","); // append a comma to the end of previous line
                    List<string> aRow = FormatAsJsonArray(line);
                    bldr.AppendLine();
                    bldr.Append("{");
                    for (int i = 0; i < headers.Length; i++)
                    {
                        bldr.Append(headers[i]);
                        bldr.Append(":\"");
                        bldr.Append(aRow[i]);
                        bldr.Append("\"");
                        if (i != headers.Length - 1)
                            bldr.Append(",");
                    }
                    bldr.Append("}");
                }
                else
                {
                    headers = line.Split(',');
                }
            }
        }
        bldr.Append(Environment.NewLine + "]" + Environment.NewLine);
        return bldr.ToString();
    }

    private List<string> FormatAsJsonArray(string aLine)
    {
        int k = 0;
        string[] tokens = aLine.Split(',');
        List<string> items = new List<string>();
        string lastPart = "";
        if (tokens.Length > 6)
        {
            for (int i = 7; i < tokens.Length; i++)
            {
                lastPart = String.Concat(lastPart, tokens[i]);
                if (i != tokens.Length - 1)
                    lastPart += ",";

            }
        }

        for (int i = 0; i < tokens.Length; i++)
        {
            if (i > 8)
                break;
            if (tokens[i].Contains("["))
            {
                List<string> msecs = MsecColumnAsJson(tokens[i]);
                for (int kk = 0; kk < msecs.Count; kk++)
                    items.Add(msecs[kk]);
            }
            else if (k < 7)
                items.Add(tokens[i]);
            k++;
        }
        if (lastPart != null && lastPart.Length > 0)
            items.Add(lastPart);

        return items;
    }

The ViewFile.cshtml contains in part.

<h2>@ViewData["name"]</h2>
<div class="container">
    <br />
    <table id="table_id" class="table table-condensed table-striped table-hover display">
        <thead>
            <tr>
                <th>DateTime</th>
                <th>Msecs</th>
                <th>Thread</th>
                <th>Level</th>
                <th>Logger</th>
                <th>Host</th>
                <th>Msg Type</th>
                <th>Message</th>
            </tr>
        </thead>
        <tbody>
            @{
            string logFile = (string)@ViewData["data"];
            var k = 0;
            }
            @foreach (string lf logFile)
            {
            if (k++ > 50)
            {
            break;
            }
            <tr>
                @foreach (string item in lf)
                {
                <td>
                    @item
                </td>
                }
            </tr>
            }
        </tbody>
    </table>
</div>

I end up getting cannot convert type 'char' to 'string' in each of the foreach statements. I tried using var for the var logFile = @ViewData["data"] line, but then the rest isn't working.

My intention was to extract on Json array line at a time, then break each of those up into a single td. How can I use the LogFileModel to contain the handling of the data, and create a view and controller to do this?

1 Answer 1

1

I would suggest going a different approach.

Use TextFieldParser from Microsoft.VisualBasic.FileIO (Yes, you can use that in C#) to read CSV and place it as data model and then use Newtonsoft.Json to create json from that objects.

Here's more on TextFieldParser: https://coding.abel.nu/2012/06/built-in-net-csv-parser/

Sign up to request clarification or add additional context in comments.

2 Comments

I've done part of that before. If you note, I am using a TextReader to read the csv. The format as Json could be replaced by what you say, of course. The question is how to extract the Json into the ViewFile.cshtml.
Simply convert it back into object structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.