@@ -278,25 +278,14 @@ public async Task SetUserAvatarAsync(Guid userId, string avatarId, string? authT
278278
279279 try
280280 {
281- // Delete old profile image file if exists
281+ // Remember the old path before making changes
282+ string ? oldProfileImagePath = null ;
282283 if ( user . ProfileImage != null && ! string . IsNullOrEmpty ( user . ProfileImage . Path ) )
283284 {
284- var oldPath = user . ProfileImage . Path ;
285- if ( File . Exists ( oldPath ) )
286- {
287- try
288- {
289- File . Delete ( oldPath ) ;
290- _logger . LogInformation ( "Deleted old profile image: {Path}" , oldPath ) ;
291- }
292- catch ( Exception ex )
293- {
294- _logger . LogWarning ( ex , "Could not delete old profile image" ) ;
295- }
296- }
285+ oldProfileImagePath = user . ProfileImage . Path ;
297286 }
298287
299- // Copy the new avatar file
288+ // Copy the new avatar file first (before deleting anything)
300289 File . Copy ( avatarPath , profileImagePath , overwrite : true ) ;
301290 _logger . LogInformation ( "Copied avatar to profile path" ) ;
302291
@@ -314,6 +303,22 @@ public async Task SetUserAvatarAsync(Guid userId, string avatarId, string? authT
314303
315304 await _userManager . UpdateUserAsync ( user ) . ConfigureAwait ( false ) ;
316305 _logger . LogInformation ( "Saved user changes to database" ) ;
306+
307+ // Delete old profile image file after the database update succeeded
308+ if ( oldProfileImagePath != null
309+ && oldProfileImagePath != profileImagePath
310+ && File . Exists ( oldProfileImagePath ) )
311+ {
312+ try
313+ {
314+ File . Delete ( oldProfileImagePath ) ;
315+ _logger . LogInformation ( "Deleted old profile image: {Path}" , oldProfileImagePath ) ;
316+ }
317+ catch ( Exception ex )
318+ {
319+ _logger . LogWarning ( ex , "Could not delete old profile image (orphan file left)" ) ;
320+ }
321+ }
317322 }
318323 catch ( Exception ex )
319324 {
0 commit comments