将对象从文本文件添加到列表

时间:2018-07-17 03:23:10

标签: c# asp.net-mvc

这是我的代码:它仅添加.txt中的第一个1(Roberto) 文本包含:

1,2343443,Roberto,洛佩兹

2,3434343,乔斯,佩雷斯

3,12123242,达里奥,吉梅内斯

0,45789432,jorge,洛佩兹

[HttpPost]
public string CargarAlumnos()
{
    List<Alumno> lstAlumnos = new List<Alumno>();
    if (Request.Files.Count > 0)
    {
        var file = Request.Files[0];

        if (file != null && file.ContentLength > 0)
        {
            StreamReader reader = new StreamReader(file.InputStream);
            do
            {
                string textLine = reader.ReadLine();
                textLine.Replace("<br>", "");
                String[] dato = textLine.Split(',');
                while (textLine != null)
                {
                        Alumno nAlu = new Alumno
                        {
                            numero = Convert.ToInt32(dato[0]),
                            cedula = dato[1],
                            nombre = dato[2],
                            apellido = dato[3]
                        };
                        lstAlumnos.Add(nAlu);
                    textLine = reader.ReadLine();
                }reader.Close();
            }while (reader.Peek() != -1);

            return "Alumnos Cargados";
        }
    }

    return "No se pudo procesar el archivo";
}

1 个答案:

答案 0 :(得分:2)

您进行了循环,这不必要地使逻辑变得复杂。以下代码对于读取文本文件非常简单。经过测试并可以正常工作。

[HttpPost]
public string CargarAlumnos()
{
    List<Alumno> lstAlumnos = new List<Alumno>();
    if (Request.Files.Count > 0)
    {
        var file = Request.Files[0];

        if (file != null && file.ContentLength > 0)
        {
            StreamReader reader = new StreamReader(file.InputStream);

            while (!reader.EndOfStream) 
            { 
                var line = reader.ReadLine(); 
                line = line.Replace("<br>", ""); 
                string[] data = line.Split(','); 

                if (data != null && data.Count() > 0) 
                { 
                    // YOUR DATA IS HERE 
                    Alumno nAlu = new Alumno
                    {
                        numero = Convert.ToInt32(data[0]),
                        cedula = data[1],
                        nombre = data[2],
                        apellido = data[3]
                    };

                    lstAlumnos.Add(nAlu);
                }
            }   
        }
    }
}