How to rename a file with appended numbers if another file already exists with the same name in asp.net c# web form application?

Hello Experts.

I'm using Visual Studio 2012 and SqlServer 2012.  

I am using a fileupload control to upload files to the web server.  Whenever a file with the same name already exists, I would like to have that filename changed by adding a number to the end.  For example, contract.docx, contract(1).docx, contract(2).docx, etc...  I have seen this question answered many time on EE, as well as Stackoverflow and other sites.  Unfotrtunately, I haven't been able to successfully modify my code to help me do that.  

The code I have right now is straight-forward, and just overwrites original files with the new file if the filenames are the same.  Here is what I have right now:

protected void btn_frm_new_doc_save_close_Click(object sender, EventArgs e)
        {
            if (fu_doc_upld.HasFile)
            {
                fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + fu_doc_upld.FileName);
            }
            hdn_filename_txt.Value = (Server.MapPath("~/Data/") + fu_doc_upld.FileName.ToString());
            hdn_doc_uplod_dt_txt.Value = DateTime.Now.ToString();

            SqlConnection idrf_cnxn = new SqlConnection("Data Source=MYSRVR;Initial Catalog=idrf;Integrated Security=True");
            {
                SqlCommand new_doc_cmd = new SqlCommand("Insert Into tbl_doc(doc_title, doc_type_list, doc_org_list, doc_dept_list, doc_desc, prior_contract_cd, legal_comp_contract_id, doc_upld_dt, doc_path, vendor_id_fk) Values(LTRIM(RTRIM(@doc_title)), LTRIM(RTRIM(@doc_type_list)), LTRIM(RTRIM(@doc_org_list)), LTRIM(RTRIM(@doc_dept_list)), LTRIM(RTRIM(@doc_desc)), LTRIM(RTRIM(@prior_contract_cd)), LTRIM(RTRIM(@legal_comp_contract_id)), LTRIM(RTRIM(@doc_upld_dt)), LTRIM(RTRIM(@doc_path)), LTRIM(RTRIM(@vendor_id_fk)))", idrf_cnxn);
                new_doc_cmd.Parameters.AddWithValue("@doc_title", doc_title_txt.Text);
                new_doc_cmd.Parameters.AddWithValue("@doc_type_list", doc_type_ddl.Text);
                new_doc_cmd.Parameters.AddWithValue("@doc_org_list", doc_org_ddl.Text);
                new_doc_cmd.Parameters.AddWithValue("@doc_dept_list", doc_dept_ddl.Text);
                new_doc_cmd.Parameters.AddWithValue("@doc_desc", doc_desc_txt.Text);
                new_doc_cmd.Parameters.AddWithValue("@prior_contract_cd", prior_contract_cd_txt.Text);
                new_doc_cmd.Parameters.AddWithValue("@legal_comp_contract_id", lgl_comp_cont_id_txt.Text);
                new_doc_cmd.Parameters.AddWithValue("@doc_upld_dt", hdn_doc_uplod_dt_txt.Value);
                new_doc_cmd.Parameters.AddWithValue("@doc_path", hdn_filename_txt.Value);
                new_doc_cmd.Parameters.AddWithValue("@vendor_id_fk", hdn_vendor_id_txt.Value);

                idrf_cnxn.Open();
                new_doc_cmd.ExecuteNonQuery();
                idrf_cnxn.Close();

                if (IsPostBack)
                {
                    Response.Redirect("~/Default.aspx");
                }
            }
        }

Open in new window


How can I modify this to not overwrite existing files with the same names, but instead rename the files as stated above?

Please let me know if you need additional information.

Your help is greatly appreciated.

Thanks,
J
ferguson_jeraldAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
int i = 0;
string filename = fu_doc_upld.FileName;
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename)))
{
   i++;
   filename = fu_doc_upld.FileName + " (" + i.ToString() + ")";    
}

fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename;

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ferguson_jeraldAuthor Commented:
Thanks Kyle!!!

It's exactly what I needed.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.