简体   繁体   中英

How to copy efficiently UNC paths in the same remote machine

I'm working on an efficient solution to copy big files in the same remote machine, let's call it FILESERVER. Then, from another server (WEBSERVER) I want to issue copies of these files remotely, so I tried to copy/paste files in the same remote shared folder with Windows Explorer and I noticed it doesn't need to move the file contents through the network, so I thought using shared folders and simply copying files from WEBSERVER could make it.

So, I gave it a try with the following code.

File.Copy("\\FILESERVER\FOLDER\bigfile", "\\FILESERVER\FOLDER2\bigfile");

This works, but I noticed that it is actually moving the file contents through the network and that's exactly what I wanted to avoid. I don't want to have to implement a server in FILESERVER to receive commands to copy files if I can do it with a built-in Windows mechanism. So the behaviour I would like to implement is the same Explorer does, invoking it from my c# code. So, is possible to do this in .NET?

EDIT : I tried XCOPY command and at first seemed it didn't use the network. But after some reboots to ensure it wasn't any OS caching involved, I noticed that when I execute XCOPY from cmd it doesn't show any I/O in Process Explorer/taskmgr, but, when I execute this command from my C# code it does. So I think it does use the network to fetch/write the file contents but for a weird reason it's not reported in these diagnostics tools (taskmgr / Process Explorer).

使用PSEXEC并在远程计算机上使用本地文件夹路径运行副本。

Definitely WMI is a good way to do it. I finally managed to do it with the following code and the CopyEx method to copy directories recursively.

var classInstance = new ManagementObject("\\\\FILESERVER\\root\\cimv2", "Win32_Directory.Name='c:\\path\\to\\directory1'", null);

var copyExInParams = classInstance.GetMethodParameters("CopyEx");

// Add the input parameters.
copyExInParams["FileName"] = "c:\\path\\to\\directory2";
copyExInParams["Recursive"] = true;
copyExInParams["StartFileName"] = null;

var copyExOutParams = classInstance.InvokeMethod("CopyEx", copyExInParams, null);

It's important to notice that paths must be in the remote machine format. I can't prove it but maybe Windows Explorer is taking advantage of WMI to copy files in the same remote machine in shared folders to prevent useless network traffic. I haven't found a way to do it directly with UNC. Even though this suits my use case.

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