Вопрос

Question background:

I am attempting to overwrite the contents of one specified file with the contents of another specified file within a folder on my C drive using the following 'File.Replace' method:

//'null' has been set to the 'backup file' parameter as I do not need this.
File.Replace(fileOnesLocation, filesTwosLocation, null);

The error:

I have the above method wrapped in a try catch and am currently receiving the following error:

System.IO.IOException: The process cannot access the file 
because it is being used by another process.

Can anyone point me in the right direction of whats going wrong here?

Это было полезно?

Решение 3

This error is often caused when the file being replaced or written to is open by you or someone/thing while the code is running.

Другие советы

If you want to avoid this errors, you could try doing something like this answer, create a method to check whether your file is open or not.

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

If the file is open either by you or another logged in user then you may not be able to open it.

check in task manager for processes by users and close the file.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top