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?
– Leonel Sanches da Silva
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.
– AbnoanMuniz
Have you tried using the result? using (Streamreader stream = new Streamreader(model.Arquivo.Inputstream)){ var Columns = stream.Readline(). Split(';'). Count(); }
– Jean Gustavo Prates