1

I've started to encounter a problem with File.Copy. This works fine for my data creation script, managing to duplicate thousands of files with no issues. My problem occurs when trying to create temp files later in my code.

I have added the code sample below that isn't working correctly. I've tried numerous different ways to try to resolve this to no avail. What I am doing is copying some user data files created in a directory on the C drive into a temp folder inside that user data folder.

Code

foreach (string originalFile in OriginalDataFileNames)
{
    string tempFile = originalFile;
    TempDataFiles.Add(tempFile);
    Console.WriteLine("GlobalDataCtrl: Original Data File: " + XWSDataDirectory + "\\" + tempFile);
    Console.WriteLine("GlobalDataCtrl: Saved Temp Data File: " + tempPath + "\\" + tempFile);
    File.Copy(XWSDataDirectory + "\\" + originalFile, tempPath + "\\" + tempFile);
}

Exit Error

The program '[6256] XtremeWrestlingSim.vshost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.

Any help is appreciated, thanks in advance!

SOLUTION:

FileStream outputFS = null;
            FileStream inputFS = null;
            outputFS = new FileStream(tempPath + "\\" + tempFile, FileMode.CreateNew, FileAccess.ReadWrite);
            using (inputFS = new FileStream(XWSDataDirectory + "\\" + originalFile, FileMode.Open))
            {
                inputFS.CopyTo(outputFS);
            }
            outputFS.Close();
            inputFS.Close();

Not sure how nicely formatted this is, but it works. Replace File.Copy with the above code.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Do you write these files yourself, and then later trying to copy them? Its possible that you're not closing a file handle somewhere. Make sure to use `using` statements or call `.Close()` any time you write a file – Adam Schiavone May 08 '17 at 22:36
  • 2
    Possible duplicate of [C# UnauthorizedAccessException in File.Copy](http://stackoverflow.com/questions/18554108/c-sharp-unauthorizedaccessexception-in-file-copy) – krillgar May 08 '17 at 22:37
  • 3
    I question why you are creating a new file (File.Create) and then copying an existing file over the top of it straight after (File.Copy). – Andrew Harris May 08 '17 at 22:41

1 Answers1

4

You are using File.Create just before you call File.Copy, I think that is the issue, it is leaving an open stream.

Maybe removing the File.Create call will solve the issue. If not you could get the returned value (which is a stream) and close it before trying to copy.

The file is opened with read/write access and must be closed before it can be opened by another application.

See remarks https://msdn.microsoft.com/en-us/library/ms143361(v=vs.110).aspx

BrunoLM
  • 97,872
  • 84
  • 296
  • 452