Search Asp.Net Here

Give Unique Name to a Uploaded File in Asp.Net (C#)



How to give unique name to a uploaded file in Asp.Net (C#)

Here in an example of how we can give unique name to a uploaded file in Asp.Net (C#) using Guid (Global unique Identifire)

Code for .aspx file is given below:

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
<asp:Label ID="Label1" runat="server"></asp:Label>

Create a folder named files in application's root directory
Now write the following code in .cs(C#) file below of page load event

protected void Button1_Click(object sender, EventArgs e)
{
string sp = Server.MapPath("files");
//MapPath method returns path till current folder(root)
//Giving a random name to uploaded File

String fn = Guid.NewGuid().ToString() + FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf("."));
if (sp.EndsWith("\\") == false)
sp += "\\";
sp += fn;//Concating file name with server path
FileUpload1.PostedFile.SaveAs(sp);//FileUpload1.PostedFile property Holds client side path
Label1.Text = "File Uploaded succefully";
}

Try it………


Comments :

1
Honey Narang said...
on 

i want to change file name before save please let me know

Post a Comment