This way
HTML
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="FileUpload" />
Namespace
using System.IO;
C#
protected void FileUpload(object sender, EventArgs e)
{
int count = 0;
string filename = string.Empty;
if (this.FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);
string[] files = Directory.GetFiles(Server.MapPath("~/Files/"));
if (File.Exists(Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName)))
{
foreach (string s in files)
{
filename = Path.GetFileName(s).Substring(0, Path.GetFileName(s).LastIndexOf("."));
if (filename.Contains("("))
{
filename = filename.Substring(0, filename.LastIndexOf("("));
}
if (filename == Path.GetFileName(FileUpload1.PostedFile.FileName).Substring(0, Path.GetFileName(FileUpload1.PostedFile.FileName).LastIndexOf(".")))
{
count++;
}
}
this.FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Files/") + filename + "(" + count.ToString() + ")" + ext);
}
else
{
this.FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName));
}
}
}
Using TextBox to change Uploaded file name
HTML
<form id="form1" runat="server">
<div>
File name =
<asp:TextBox ID="txtFileName" Text="SaharaDesert" runat="server" />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="FileUpload" />
</div>
</form>
C#
protected void FileUpload(object sender, EventArgs e)
{
int count = 0;
if (this.FileUpload1.HasFile && !string.IsNullOrEmpty(this.txtFileName.Text))
{
string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);
string[] files = Directory.GetFiles(Server.MapPath("~/Files/"));
if (File.Exists(Server.MapPath("~/Files/") + this.txtFileName.Text + ext))
{
foreach (string s in files)
{
string filename = string.Empty;
filename = Path.GetFileName(s).Substring(0, Path.GetFileName(s).LastIndexOf("."));
if (filename.Contains("("))
{
filename = filename.Substring(0, filename.LastIndexOf("("));
}
if (filename == this.txtFileName.Text.Trim())
{
count++;
}
}
this.FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Files/") + this.txtFileName.Text + "(" + count.ToString() + ")" + ext);
}
else
{
this.FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Files/") + this.txtFileName.Text + ext);
}
}
}