Search code examples
c#overwritefile-copying

(File.Copy) Unhandled 'System.IO.IOException' in mscorlib.dll


I have a problem with copying files, if file exists in target directory, overwrite it, else do nothing. But I'm getting this error message:

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
The process cannot access the file [PATH]/TaskRepository.cs 
because it is being used by another process.  

I haven't found a solution for hours even. Looked for other topics on stackoverflow but couldn't figure out. My code is here

public void EditFiles(List<string> OriginalFiles, List<string> TargetFiles)
{
    foreach (var original in OriginalFiles)
    {
        int i = 0;
        int index = original.LastIndexOf(@"\");
        if (original.Substring(index).Contains("TaskRepository.cs"))
        {
            while (i < TargetFiles.Count)
            {
                if (TargetFiles[i].Contains("TaskRepository.cs") == true)
                {
                    File.Copy(original, TargetFiles[i], true);
                }
                i++;
            }
        }                
    }
}

Solution

  • I would try copying the files you want to work with to a separate folder. Visual Studio is most likely the culprit but it could be anything locking the files.

    Visual Studio locking files while debugging