the process cannot access the file 'uploaddoc.xls' because it is being used by another process

Posted by Prabu_Spark under ASP.NET on 6/12/2013 | Points: 10 | Views : 2066 | Status : [Member] | Replies : 1
Hi sir,
I upload one excel file and get the records from that excel file and stored in database. After finish storing the records in the database,
i need to delete the file stored in "uploaded" folder. If i try to delete the file it shows error like "the process cannot access the file 'uploaddoc.xls' because it is being used by another process". I shared the code. Kindly give me the solution for this problem.


protected void Button1_Click(object sender, EventArgs e)
{
try
{
//System.Threading.Thread.Sleep(5000);

if (FileUpload1.HasFile)
{

string filename = FileUpload1.FileName;

string checking_ext = Path.GetExtension(filename);

if (checking_ext == ".xls")
{
string file_location = Server.MapPath("uploads/" + filename);
string count;
FileUpload1.SaveAs(file_location);
import_excel(file_location, out count);
lbl_count.Text = count;
}
else
{
lbl_error.Text = "Please select the excel file";
}
}
else
{
lbl_error.Text = "Please select the file";
}
}
catch (Exception ex)
{
ErrorHandler.WriteError(ex.Message.ToString());
}

}


private void import_excel(string path, out string cnt)
{
try
{
OleDbConnection con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties=Excel 8.0;");
OleDbCommand cmd;
con.Open();
cmd = new OleDbCommand("select * from [Sheet1$]", con);

DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter();
oda.SelectCommand = cmd;
oda.Fill(ds);



Session["total_count"] = cnt;
Response.Redirect("Process1.aspx");


if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
}
catch (Exception ex)
{
if (ex.Message == "External table is not in the expected format.")
{
lbl_error.Visible = true;
lbl_error.Text = "Invalid File Format";

}
else if (ex.Message == "'Sheet1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long." || ex.Message == "No value given for one or more required parameters.")
{
lbl_error.Visible = true;
lbl_error.Text = "Invalid Excel Sheet";

}
cnt = "";

ErrorHandler.WriteError(ex.Message.ToString());

}
}

With regards,
J.Prabu.
[Email:prbspark@gmail.com]



Responses

Posted by: Rickeybglr on: 6/13/2013 [Member] Starter | Points: 25

Up
0
Down
before delete dnt forget to close the connection

Prabu_Spark, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response