简体   繁体   中英

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" . 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.

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. 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. This confused me because I supposed that if cmd command creates the dir also Copy method can manage this case. 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.

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