How to count columns of an Httppostedfilebase txt file?

Asked

Viewed 812 times

4

In the code below, it would work perfectly if I had access to path of the file uploaded on the client side, however, it doesn’t work that way. So I’d like to ask you guys to suggest 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.");
            }    

I appreciate all the answers.

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

But I was unsuccessful.

Edit:

How is the entrance:

Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field
Field; field; field; field ; field

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

  • In this test you did, what expected behavior and what behavior actually occurred?

  • The result was exactly as expected, he performed the Count of the columns separated by ';' in the file. Validating row by row, works perfectly. But as I said before, I can’t recover the file path. The ideal scenario is from the file I have inside the model, I can do the Count of the columns. Of course it is exactly the same file.

  • Have you tried using the result? using (Streamreader stream = new Streamreader(model.Arquivo.Inputstream)){ var Columns = stream.Readline(). Split(';'). Count(); }

2 answers

2

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

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

Your View needs a file upload field:

@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, 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:

inserir a descrição da imagem aqui

  • I just did the test, but for my input it didn’t work. I will edit the initial post with input.

  • Dude, your answer wasn’t what I wanted, but it led me to solve my problem. Thanks.

  • 1

    Glad my answer was helpful and helped solve the problem :-)

0


Based on @Renan’s reply

I came to this conclusion that Sana 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 resolved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.