File.Copy(sourceFileName,destFileName,overwrite) does not work on some OS

时间:2015-11-12 12:07:01

标签: c# system.io.file

I am seeing weird errors with the following code snippet:

File.Copy(oldPath, targetPath,true);
File.SetAttributes(targetPath, FileAttributes.Normal);

A file has to be moved somewhere else, and because I lack write right at the source path, I copy the file and set access rights for the destination file. On my system (Windows 7 SP1) this works fine.

However, on (as far as I know) any Windows 10 machine the program crashes at File.SetAttributes with the message

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Could not find file 'C:\ProgramData\...\BlankDb.sdf'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.SetAttributes(String path, FileAttributes fileAttributes)

This tells me even though the code has passed the File.Copy() line, the file has not yet been copied successfully. Does File.Copy() not work synchronously anymore, or has anything else changed on differing OS in this regard?

Quite frankly, I am stumped. At first I thought of timing issues and tried wrapping the Copy call in a new Thread, until I read the File.Copy() will not return anyways before copying successfully or running into an error.

3 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码。 (请改变你的路径)

 static void Main(string[] args)
    {
        var oldDir = new DirectoryInfo("D:\\Personal\\Projects\\Desktop\\StackSolutions\\ConsoleApp1\\ConsoleApp1\\OldFilePath\\funy.jpg");
        var newDir = new DirectoryInfo("D:\\Personal\\Projects\\Desktop\\StackSolutions\\ConsoleApp1\\ConsoleApp1\\NewFilePath\\funy1.jpg");

        var oldPath = oldDir.FullName;
        var targetPath = newDir.FullName;

        File.Copy(oldPath, targetPath);
        File.SetAttributes(targetPath, FileAttributes.Normal);
    }

答案 1 :(得分:0)

您只需将复制的文件自己写入目标位置即可完全绕开File.Copy()。

latitude, longitude = zip(*[(x1[i], x2[i]) for i in range(1,len(x1) - 1)])

确保将占位符替换为引用源文件和目标文件的字符串。 这将简单地一次复制源文件,一次2MB,直到复制所有数据。

答案 2 :(得分:-1)

您可以尝试共享目录' C:\ ProgramData ...'如果是因为Windows 10上的权限问题,它就会解决问题。

您可以参考http://www.geeksquad.co.uk/articles/how-to-set-up-file-sharing-on-windows-10获取帮助以共享您的文件夹。