Tuesday, March 22, 2022

C# Copy File But Error because it is being used by another process

Error: because it is being used by another process.

I get this error when using File.Copy(fileSource, fileTarget, true);

Not exactly the solution from stackoverflow, but this is the solution that I used:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
try
{
    File.Copy(fileSource, fileTarget, true);
}
catch (IOException e)
{
    if (e.Message.Contains("in use"))
    {

        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/C copy \"" + fileSource + "\" \"" + fileTarget + "\"";
        p.Start();
        Console.WriteLine(p.StandardOutput.ReadToEnd());
        p.WaitForExit();
        p.Close();
    }
}

I don't know why this works though. Before I had to go to the physical server, rename the file, then copy. I still do not know why the files are locked. Nothing should be running it. This is not a problem with all applications running on the server.


Reference

https://stackoverflow.com/questions/6167136/how-to-copy-a-file-while-it-is-being-used-by-another-process

No comments:

Post a Comment