Search code examples
c#sqlsql-serverstreamreader

Inserting a txt file into database


public partial class Form1 : Form
{

    public SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Alexander\Desktop\Archivos.mdf;Integrated Security=True;Connect Timeout=30");



    private void Readbtn_Click(object sender, EventArgs e)
    {
         con.Open();
         Propiedades prop = new Propiedades();
         List<string> myValues = new List<string>();

         string line;

       StreamReader file = new StreamReader(@"c:\temp\archivo.txt");
        if ((line = file.ReadLine()) != null)
        {
            string[] fields = line.Split(',');
            prop.matricula = fields[0].ToString();
            prop.nombre = fields[1].ToString();
            prop.sueldo = decimal.Parse(fields[2]); 

            for (int i = 0; i < fields.Length; i++)
            {
                listBox1.Items.Add(fields[i]);
            }

        }



     SqlCommand cmd = new SqlCommand("INSERT INTO Archivos(Codigo, Nombre, Sueldo) VALUES (@Matricula, @Nombre, @Sueldo", con);
     cmd.Parameters.AddWithValue("@Matricula", prop.matricula);
     cmd.Parameters.AddWithValue("@Nombre", prop.nombre);
     cmd.Parameters.AddWithValue("@Sueldo", prop.sueldo);
     cmd.ExecuteNonQuery();

     con.Close();


 }

Hello Guys, I just need a little bit of help on modifying this code. I already have this to save the first line of the text file but I dont have any ideas on how to make it read the other lines. Also I would like to validate that if the SQL table contains already that info, it will launch an exception or message box letting the user know that the file already exist. Please help


Solution

  • There are a few things you need to do the the first that jumps out at me is that you want to use a while loop in place of your first if statement

        while ((line = file.ReadLine()) != null)
        {
            string[] fields = line.Split(',');
            prop.matricula = fields[0].ToString();
            prop.nombre = fields[1].ToString();
            prop.sueldo = decimal.Parse(fields[2]); 
    
            for (int i = 0; i < fields.Length; i++)
            {
                listBox1.Items.Add(fields[i]);
            }
    
        }
    

    Also depending how you want to display the items in the list box you may want to use instead of that internal for loop:

    listBox1.Items.Add(prop.matricula+','+prop.nombre+',prop.sueldo.toString());