How to count columns from a txt file HttpPostedFileBase?

4

In the code below, it would work perfectly if I had access to the path of the uploaded file on the client side, however, it does not work that way. So I'd like to ask your suggestion for another way to do this.

Basically I need a column counter, however my file is in memory, since it is a HttpPostedFileBase .

   string result = new StreamReader(model.Arquivo.InputStream).ReadToEnd();
            var lines = System.IO.File.ReadAllLines(@"caminhoQualquer\arquivorandom.txt", Encoding.UTF7);             
            for (int i = 0; i < lines.Length; i++)
            {
                var columns = lines[i].Split(';').Count();
                if(columns > 9)
                    throw new Exception("Não foi possível importar, pois o arquivo não tem a quantidade de colunas esperadas.");
            }    

Thank you for all the answers.

Note: On the path question, I opened this topic yesterday: How to get the path of a file (HttpPostedFileBase)?

But I did not succeed.

Edit:

How the entry is:

Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field Field; field; field; campfield; field

In this case, the system would have to validate row by row the number of columns, if by chance one row has more columns than the parameterized amount, will raise the error.

    
asked by anonymous 27.10.2015 / 15:10

2 answers

0

Based on @Renan's response

I came to this conclusion that heals my problem:

public bool ValidarArquivo(ArquivoImportacaoModel model)
    {
        //List<string> conteudoArquivo = new List<string>();
        int colunas = 0;
        using (StreamReader reader = new StreamReader(model.Arquivo.InputStream))
        {
            while (!reader.EndOfStream)
            {
                //conteudoArquivo.Add(reader.ReadLine());
                colunas = reader.ReadLine().Split(';').Count();

                if (colunas > 9)
                    throw new Exception("Não foi possível importar, pois o arquivo não tem a quantidade de colunas esperadas.");
            }

        }
        return true;
    }

In this way you have resolved.

    
27.10.2015 / 18:54
2

You need to create an action on your Controller to receive the file:

        //Importando arquivos
        public ActionResult Importar()
        {
            return View();
        }       

Your View needs a field to upload the file:

@using (Html.BeginForm("Importar", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.Arquivo, new { type = "file" })
    <input type="submit" value="Importar">
}

Create a method in your Model to read the contents of your file:

    public class ImportacaoArquivo
    {
        [Required(ErrorMessage = "O Arquivo é obrigatório.")]
        public HttpPostedFileBase Arquivo { get; set; }

        internal String RetornarConteudoArquivo(Stream fileStream)
        {
            String conteudoArquivo;
            using(StreamReader reader = new StreamReader(fileStream))
            {
                conteudoArquivo = reader.ReadToEnd();
            }
            return conteudoArquivo;
        }
    }

You can get the number of columns in the file using the split () method, for example:

        [HttpPost]
        public ActionResult Importar(ImportacaoArquivo importacaoArquivo) 
        {
            var conteudo = String.Empty;
            if(importacaoArquivo.Arquivo.ContentLength > 0)
            {
                conteudo = importacaoArquivo.RetornarConteudoArquivo(importacaoArquivo.Arquivo.InputStream);
            }

            var totalColunas = conteudo.Split(';').Length;

            ViewData["conteudo"] = conteudo;
            ViewData["totalColunas"] = totalColunas;
            return Content("<b>Conteúdo: </b>" + conteudo + "<br><b>Total de Colunas: </b>" + totalColunas);
        }

The result would be something like:

    
27.10.2015 / 17:14