vinothkannan M
vinothkannan M

Reputation: 81

how to change the filename to save in particular folder

I have to change the file name from the upload file and with the changed file name need to store in my folder for example (uploaded file: employee.xlsx) name changed to (employee + datetimenow).xlsx . Below I have given my web api coding

Code

{
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filename = postedFile.FileName;
            var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
        return Request.CreateResponse("Uploaded Successfully!");
    }
    return Request.CreateResponse("Failed");
}

Upvotes: 2

Views: 1550

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29036

Modify your looping as like the following:

 foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var fileextension =new FileInfo(postedFile.FileName).Extension();
            var filePath = HttpContext.Current.Server.MapPath("~/yourFileName." + fileextension);
            postedFile.SaveAs(filePath);
        }

Upvotes: 1

Mohit S
Mohit S

Reputation: 14064

This might do the trick for you

var filename = postedFile.FileName;
var FileNameOnly  =  Path.GetFileNameWithoutExtension(fileName);
Var fileExt = Path.GetExtension(fileName);
var ModFileName = FileNameOnly + DateTime.Now + fileExt;
var filePath = HttpContext.Current.Server.MapPath("~/" + ModFileName);
postedFile.SaveAs(filePath);

Upvotes: 2

Related Questions