Search code examples
c#fileasp.net-corebitmapfile-location

deleting and creating new/overwriting file with same name c# .NET


I'm trying to save pictures in a folder and every hour I want to save new pictures with the same name as the old ones. I've tried deleting the old pics, and when debugging, they get deleted but when I try to create new versions with the same name, the picture reappears with the old date and time.

This is my code:

 public void SaveThumbnailsToFolder(List<Thumbnail> thumbnails, Profile p)      {

            foreach (Thumbnail thumbnail in thumbnails)
            {
                Bitmap image = new Bitmap(thumbnail.Image);
                try
                {
                    string path = Path.Combine(p.ThumbnailDownloadFileLocation, String.Format(thumbnail.Name + ".jpg"));
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    image.Save(path);
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
            }
        }

Any ideas of what I'm doing wrong?


Solution

  • but when I try to create new versions with the same name, the picture reappears with the old date and time.

    For this problem, you can use SetCreationTimeUtc after saving the image to ensure that the image creation time is the current time.

     image.Save(path);
     File.SetCreationTimeUtc(path, DateTime.UtcNow);
    

    Here is my test result:

    enter image description here