简体   繁体   English

C# File.Copy 从远程计算机到本地

[英]C# File.Copy from remote computer to local

When I try to copy an existing file from a remote computer to local with当我尝试将现有文件从远程计算机复制到本地时

File.Copy(
string.Format(@"\\{0}\e$\{1}", computerName, fileName), 
string.Format(@"{0}\{1}\{2}", localPath, computerName, fileName), 
true);

I get the Exception Could not find part of the path "\\computername\e$\filename" .我得到 Exception Could not find part of the path "\\computername\e$\filename" I checked the path and it's correct.我检查了路径,它是正确的。

I don't think that is a permission problem beacuse I can reach the file with Directory.GetFiles and I can obtain info like file size or last writing date with FileInfo , moreover when I execute xcopy command from cmd with the same paths in the code he copies the file sucessfully.我认为这不是权限问题,因为我可以使用Directory.GetFiles访问文件,并且可以使用FileInfo获取文件大小或上次写入日期等信息,此外,当我从 cmd 使用代码中相同的路径执行 xcopy 命令时他成功地复制了文件。

Can anyone help me to understand what I do wrong or other ways to copy file?谁能帮助我了解我做错了什么或其他复制文件的方法?

Copying from or to a remote location is not done by using the normal File.Copy since there's a difference if the files are saved on the local HDD or if they are accesible by your network.使用普通的 File.Copy 不能从远程位置复制或复制到远程位置,因为文件是保存在本地 HDD 上还是可以通过网络访问是不同的。 Other community members already worked out a few solutions.其他社区成员已经制定了一些解决方案。 The easiest one might be this:最简单的可能是这样的:

How to provide user name and password when connecting to a network share 连接到网络共享时如何提供用户名和密码

another solution is provied in this thread:此线程中提供了另一种解决方案:

Copying a file to a network share i dont have access to 将文件复制到我无权访问的网络共享

You need to find out which suits you best.你需要找出最适合你的。 It's important to mention that your program might not be runnable from everywhere and by everyone if you skip the Impersonation.重要的是要提到,如果您跳过模拟,您的程序可能无法从任何地方和所有人运行。 Which could prevent users from a failure free working.这可以防止用户无故障工作。

I discovered that File.Copy doesn't create the given destination folder if it doesn't exist, unlike xcopy command.我发现File.Copy不会创建给定的目标文件夹,如果它不存在,不像xcopy命令。 This confused me because I supposed that if cmd command creates the dir also Copy method can manage this case.这让我很困惑,因为我认为如果 cmd 命令创建 dir 也Copy方法可以管理这种情况。 Moreover the Exception message specified that the source path was wrong instead of the destination path.此外,异常消息指定源路径错误,而不是目标路径。

So to solve the problem:所以要解决这个问题:

localPath = Path.Combine(localPath, computerName);
if (!Directory.Exists(localPath))
{
    Directory.CreateDirectory(localPath);
}
File.Copy(
string.Format(@"\\{0}\e$\{1}", computerName, fileName), 
Path.Combine(localPath, fileName), 
true);

I apologize for my not so good english and for distraction.我为我不太好的英语和分心道歉。

Thanks for the help.谢谢您的帮助。

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

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