Home > Mobile >  Replace filename using create.PostedFile.FileName C#
Replace filename using create.PostedFile.FileName C#

Time:01-03

How to replace filename using that code. I tried to search. but could not find it. File 'C:\Program Files (x86)\IIS Express\1.heic' is not found.

        if (Path.GetExtension(create.PostedFile.FileName).ToLower() == ".heic")
        {
            File.Move(create.PostedFile.FileName, Path.ChangeExtension(create.PostedFile.FileName, ".jpg"));
        }

CodePudding user response:

Path.GetExtenstion is a function that is returning a string to you. It doesnt make any changes. To rename file you could move the file. It could be done using this code:

public void RenameFile(string fullNamePath, string newFileName)
{
    var newPath = Path.Combine(Path.GetDirectoryName(fullNamePath), newFileName   Path.GetExtension(newFileName));
    System.IO.File.Move(fullNamePath, newFilePath);
}

You could call this function like:

RenameFile("C:/oldfilename.jpg","newFileName.png");

CodePudding user response:

you could use File.Move method:

File.Move(myffile, Path.ChangeExtension("C:/oldfilename.jpg", ".jpg"));

CodePudding user response:

You need to create a folder in the web directory to save the files and then save the file.

string path = Server.MapPath("~/uploads/");
if (!Directory.Exists(path))
{
     Directory.CreateDirectory(path);
}
            
if (Path.GetExtension(create.PostedFile.FileName).ToLower() == ".heic")
{
   create.PostedFile.SaveAs(path   Path.ChangeExtension(create.PostedFile.FileName, ".jpg"));
}
   
            
           
 
  •  Tags:  
  • c#
  • Related