Mainly due to two possible causes:
1) Lack of sufficient permissions to delete the file
Solution:
Give permissions on the file (s) for the user that executes your application, normally the write permission allows you to erase, however if you use the extended Windows permissions there is a Delete permission.
Define, view, change or remove file and folder permissions
An easy way (not the most recommended) is to grant Total Control permissions over the entire folder via code would be something like this:
DirectorySecurity sec = Directory.GetAccessControl(path);
// Using this instead of the "Everyone" string means we work on non-English systems.
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(path, sec);
source: link
2) The file is in use by another process:
Solution :
Make sure that it is not your program that has "grabbed" the file in some other routine: using variables by method, not global, nor by procedures, closing file access streams, etc.
If not, you can see which process has "grabbed" the file with Process Explorer from Sysinternals, following the steps on this page:
How to delete, move or rename files blocked by Windows
Although Process Explorer allows you to release the file, I recommend focusing on finding the reason why it is blocked so that the lock does not repeat and your application is released. The antivirus can be a cause.