Insert (Save) unique file in Folder (Directory) and Path in Database using C# and VB.Net in ASP.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

question regarding file upload overwrite with same name.

[Solved] File Upload overwrite with same name using C# in ASP.Net

This is the code:

filemailerupl.SaveAs(Server.MapPath("~/mailers/" + DateTime.Now.ToString("ddMMyyyy_HH_mm_ss") + "_" + filename));

My issue is here now is:

Suppose i am uploading html file with the name xyz.

In mailers folder, it is saving as 05062019_01_07_16_xyz.html.

In Database table, it is saving as 05062019_01_07_17_xyz.html.

As you can see in both, there is a difference of seconds. (difference of 1 second).

So when i am going to click on view mailer image, it says file not found.

How can i resolve this? Here Seconds is creating the problem.

i changed it to 

filemailerupl.SaveAs(Server.MapPath("~/mailers/" + DateTime.Now.ToString("ddMMyyyy_HH_mm") + "_" + filename));
command.Parameters.AddWithValue("?mailer", DateTime.Now.ToString("ddMMyyyy_HH_mm") + "_" + filename);

it will work but what if user will use the same filename in that minute only. It will overwrite.

Posted 3 months ago

Hi chetan,

Refer below sample.

HTML

<asp:FileUpload runat="server" ID="filemailerupl" />
<asp:Button Text="Upload" runat="server" OnClick="Upload" />
<hr />
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Image Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:ImageField DataImageUrlField="Path" HeaderText="Image" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

VB.Net

Imports System.IO
Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblFilespath", conn))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                gvImages.DataSource = dt;
                gvImages.DataBind();
            }
        }
    }
}

protected void Upload(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(filemailerupl.PostedFile.FileName);
    string filePath = "~/mailers/" + DateTime.Now.ToString("ddMMyyyy_HH_mm_ss") + "_" + fileName;
    filemailerupl.SaveAs(Server.MapPath(filePath));
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string sql = "INSERT INTO tblFilespath VALUES(@Name, @Path)";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddWithValue("@Name", fileName);
            cmd.Parameters.AddWithValue("@Path", filePath);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using conn As SqlConnection = New SqlConnection(constr)
            Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM tblFilespath", conn)
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                gvImages.DataSource = dt
                gvImages.DataBind()
            End Using
        End Using
    End If
End Sub

Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
    Dim fileName As String = Path.GetFileName(filemailerupl.PostedFile.FileName)
    Dim filePath As String = "~/mailers/" & DateTime.Now.ToString("ddMMyyyy_HH_mm_ss") & "_" & fileName
    filemailerupl.SaveAs(Server.MapPath(filePath))
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using conn As SqlConnection = New SqlConnection(constr)
        Dim sql As String = "INSERT INTO tblFilespath VALUES(@Name, @Path)"
        Using cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("@Name", fileName)
            cmd.Parameters.AddWithValue("@Path", filePath)
            conn.Open()
            cmd.ExecuteNonQuery()
            conn.Close()
        End Using
    End Using

    Response.Redirect(Request.Url.AbsoluteUri)
End Sub

Screenshot