简体   繁体   English

File.Copy 未经授权的访问 C#

[英]File.Copy Unauthorized access C#

I've started to encounter a problem with File.Copy .我开始遇到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.我正在做的是将在 C 驱动器上的目录中创建的一些用户数据文件复制到该用户数据文件夹内的临时文件夹中。

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.用上面的代码替换File.Copy

You are using File.Create just before you call File.Copy , I think that is the issue, it is leaving an open stream.您在调用File.Copy之前正在使用File.Create ,我认为这就是问题所在,它正在留下一个开放的流。

Maybe removing the File.Create call will solve the issue.也许删除File.Create调用将解决问题。 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请参阅备注https://msdn.microsoft.com/en-us/library/ms143361(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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