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

1.3k Views Asked by At

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?

3

There are 3 best solutions below

0
LouraQ On BEST ANSWER

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

0
Stekeblad On

If the file is actually deleted but reappear with the same date, then my guess is that the operating system sets the date using meta data inside the image file. You could try changing the modified date your self

File.SetLastWriteTime(path, DateTime.Now);

Look at the below image showing the properties dialog for a file on Windows, the modified date is before the creation date.

File modified date is earlier than creation date

0
dxiv On

Assuming the question is about file creation timestamps, this is an old and documented behavior of Windows. From the Remarks for the GetFileTime function:

If you rename or delete a file, then restore it shortly thereafter, Windows searches the cache for file information to restore. Cached information includes its short/long name pair and creation time.


[ EDIT ]   More background in Raymond Chen's The apocryphal history of file system tunnelling:

Why does tunneling exist at all?

When you use a program to edit an existing file, then save it, you expect the original creation timestamp to be preserved, since you’re editing a file, not creating a new one. But internally, many programs save a file by performing a combination of save, delete, and rename operations (such as the ones listed in the linked article), and without tunneling, the creation time of the file would seem to change even though from the end user’s point of view, no file got created.