Saad Soliman
Saad Soliman

Reputation: 82

How to rename File in FileUpload Control Asp.net?

I've Method that carry the uploaded Image and I need to rename it to have Fixed Name in my application But when using File.Copy Method it returns result with (File not Exist) I don't Know how is that

I tried This File.Copy (UploadFile.FileName, newFilName); also not responding

 string filename = Path.GetFileName(FileUpload.FileName);
                string extension = Path.GetExtension(FileUpload.PostedFile.FileName);

                string oldFileName = FileUpload.FileName;
                string newFileName = ("aboutusImage" + extension);

                File.Copy(oldFileName, newFileName);
                File.Delete(oldFileName);

                File.Move(FileUpload.FileName, newFileName);
                FileUpload.SaveAs(Server.MapPath("~/Styles/aboutusImages/") + newFileName);

                var updateAboutus = (from a in dbContext.DynamicText
                                     where a.Id == 1
                                     select a).Single();
                updateAboutus.Id = updateAboutus.Id;
                updateAboutus.Name = updateAboutus.Name;
                updateAboutus.Image = Path.Combine("~/Styles/aboutusImages/", "aboutusImage.jpg");

                dbContext.SaveChanges();

Upvotes: 1

Views: 5031

Answers (2)

merlin2011
merlin2011

Reputation: 75565

The name you are trying to move from is just the name that was given on the client side, not the current name on the server. It is probably on some temporary location on the server.

You probably want the FileUpload.SaveAs function.

Upvotes: 1

Steve
Steve

Reputation: 216293

FileUpload.FileName property represents the file name on the client machine, not on your server. Trying to File.Copy on it have very few possibility to succeed unless you have the same file in your own server in the current folder.

From the MSDN example

protected void UploadButton_Click(object sender, EventArgs e)
{
    // Specify the path on the server to
    // save the uploaded file to.
    String savePath = @"c:\temp\uploads\";

    // Before attempting to perform operations
    // on the file, verify that the FileUpload 
    // control contains a file.
    if (FileUpload1.HasFile)
    {

      String fileName = FileUpload1.FileName;

      // Append the name of the file to upload to the path.
      savePath += fileName;


      // Call the SaveAs method to save the 
      // uploaded file to the specified path.
      // This example does not perform all
      // the necessary error checking.               
      // If a file with the same name
      // already exists in the specified path,  
      // the uploaded file overwrites it.
      FileUpload1.SaveAs(savePath);

Of course, the following File.Delete, File.Move have the same problem and should be removed

Upvotes: 2

Related Questions