error when uploading txt file in gridview c # .net

1

I have this error when loading again the same file.txt when doing it the first time if it shows it without any problem the second time it throws me an error that the file is being used and tried several methods and nothing this is the code I use to upload the file

 protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        if (ChecarExtension(FileUpload1.FileName))
        {
            FileUpload1.SaveAs(@"C:\texto/" + FileUpload1.FileName);


            Label1.Text = FileUpload1.FileName + " cargado exitosamente";

            lblOculto.Text = (@"C:\texto/" + FileUpload1.FileName);
        }
    }
    else
    {
        Label1.Text = "Error al subir el archivo o no es el tipo .txt";
    }

    try
    {

        CargarDatos(lblOculto.Text);
    }
    catch
    {
        Response.Write("Ocurrio un error debe cargar antes el archivo");
    }
}

code upload data

   private void CargarDatos(string strm)
{
    DataTable tabla = null;
    StreamReader lector = new StreamReader(strm);
    String fila = String.Empty;
    Int32 cantidad = 0;
    do
    {
        fila = lector.ReadLine();
        if (fila == null)
        {
            break;
        }
        if (0 == cantidad++)
        {
            tabla = this.CrearTabla(fila);
        }
        this.AgregarFila(fila, tabla);
    } while (true);

    GridView1.DataSource = tabla;
    GridView1.DataBind();
}
    
asked by Alexander Villalobos 28.03.2017 в 20:59
source

1 answer

0

I did this fast to try and it works every time without error

protected void Button1_Click(object sender, EventArgs e)
{
    StreamReader objReader = new StreamReader(FileUpload1.FileName);
    string strLinea = "";
    ArrayList arrText = new ArrayList();
    DataTable table = new DataTable();
    table.Columns.Add("Valor", typeof(System.String));
    DataRow row;

    while (strLinea != null)
    {
        row = table.NewRow();
        strLinea = objReader.ReadLine();
        if (strLinea != null)
        {
            row["Valor"] = strLinea;
            table.Rows.Add(row);       
        }
    }
    GridView1.DataSource = table;
    GridView1.DataBind();
    objReader.Close();
    objReader.Dispose();
}

Probably adding

objReader.Close();
objReader.Dispose();

In your case the variable reader

    
answered by 28.03.2017 / 22:00
source