简体   繁体   中英

File.Copy Unauthorized access C#

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM