Changing File Name and Extension Name while Uploading Files to Server using ASP.NET


Introduction

Many times a web developer requires changing the file name, extension name at server. You can find ton of articles over web but I am here with some new mysteries.

Why (a practical use)?

In my one the recent web project needed to accept the photograph for new online registrations or may be called as create a new account and upload user’s image.  For this my team members suggested to upload that in database and etc. But my suggestion where accepted by team because I suggested to upload the photograph file of the users with new file name equals to his username and any extension to .jpg.

In C#, Path class has ton of properties and they can be used to accomplish such tasks. Look at the image given below.





Find the working code given below:

MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);
string username = CurrentUser.UserName;
String root = Server.MapPath("~");

string fileExt = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fullPath = Path.GetFullPath(FileUpload1.PostedFile.FileName);

string userImageName = username + fileExt;

string svPath = root + "/Profile/Users/images/" + userImageName;

FileUpload1.PostedFile.SaveAs(svPath);
Label1.Text = FileUpload1.PostedFile.FileName + " upload success from " + fullPath + " to " + svPath;

I hope you like this.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System