- How to rename file when upload in FileUpload

Rename uploaded file
FileUpload is an web server control that allow users to upload a file to web server from their local computer. FileUpload server control display a text box and a browse button on web browser to select a file to upload from client's local machine.

FileUpload control does not automatically save the uploaded file to web server. FileUpload SaveAs() method allow us to save the contents of a client uploaded file to web server hard disk in a specified path. Using the FileUpload control's HasFile property we can verify that the FileUpload control contains a file.

FileUpload control's FileName property get the client uploaded file name. FileUpload control's PostedFile property allow us to get the additional properties on the uploaded file such as FileName, ContentLength, ContentType etc.

We can change the client uploaded default file name by using FileUpload control's SaveAs method. SaveAs() method require to pass a parameter named filename. This parameter value is a string that specifies the full path of the location of the server on which to save the uploaded file. using this parameter we can pass a new file name instead client uploaded file name. In the next paragraph we describe few techniques to do it.

First we specify a folder on web server to save the uploaded file. Next we get the client uploaded file's extension using Path.GetExtension(path) method. This method exists in System.IO namespace. Now we call the FileUpload SaveAs() method and pass a newly generated file name to save the uploaded file. We generate a new path using adding three strings. first string is the server folder location to save file, second is a new file name without extension instead client file name and third is the client uploaded file's extension. This is a simple process to rename a file when save a uploaded file to web server.

the following example code demonstrate us how can we rename client uploaded file when saving it in web server.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        string uploadFolder = Request.PhysicalApplicationPath + "UploadFile\\";
        if (FileUpload1.HasFile)
            string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            FileUpload1.SaveAs(uploadFolder + "Test"+ extension);
            Label1.Text = "File uploaded successfully as: " + "Test"+ extension;
            Label1.Text = "First select a file.";

<html xmlns="">
<head id="Head1" runat="server">
    <title> FileUpload example: how to rename file when upload (change file name when upload)</title>
    <form id="form1" runat="server">
        <h2 style="color:Green"> FileUpload example: File Rename</h2>
        <br /><br />
             Text="Upload It"
More examples