When you upload a file in asp.net web application and if the file exists it just simply overwrites the existing file. In this example, what we are trying to do is check the filename if it exists. If exists then add an increment number at the end of the file and save in the desired location. The snippet shows only the aspx code and c# code behind codes. In this example, i am trying to upload image file and show a preview of the uploaded image and show the file name as well.

aspx

<asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
<asp:Image ID="Image1" runat="server" /><br />
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />

C# code behind

protected void Button1_Click(object sender, EventArgs e)
{
string virtualFolder = "~/images/";
string physicalFolder = Server.MapPath(virtualFolder);
int count = 1;

string fileNameOnly = Path.GetFileNameWithoutExtension(FileUpload1.FileName);
string extension = Path.GetExtension(FileUpload1.FileName);
string NewFileName = FileUpload1.FileName.ToLower();

string FullPath = physicalFolder + NewFileName;

while (File.Exists(physicalFolder + NewFileName))
{
count = count + 1;
string tempFileName = string.Format("{0}-{1}", fileNameOnly, count);
NewFileName = tempFileName + extension;
}

FileUpload1.SaveAs(physicalFolder + NewFileName);

Label1.Text = "Your file " + NewFileName + " has been uploaded.";

Image1.Visible = true;

Image1.ImageUrl = virtualFolder + NewFileName;
}