简体   繁体   中英

How to copy file from remote system to local system using C# (connected in same LAN network)?

Two computers are connected in same LAN network. I am trying to copy a file from remote system to my local system using C#. But I cannot able to copy the file from remote system. But I can able to make copies in the remote system itself.

This is to execute WQL (WMI Queries) in the remote system

ObjectQuery query = new ObjectQuery("SELECT * FROM CIM_DataFile WHERE 
       FileName='test' AND Extension='txt'");
ManagementObjectSearcher  searcher = new ManagementObjectSearcher(scope, query);
queryCollection = searcher.Get();

ManagementBaseObject inParams, outParams;
string localPath = "C:\\Users\\UserName\\Desktop\\log.txt";
string remotePath = "\\\\RemoteComputer\\C:\\Folder1\\Testing\\test.txt";

foreach (ManagementObject m in queryCollection)
{
    // Display the remote file information in local system 
    Console.WriteLine("Name         :{0}", m["Name"]);
    Console.WriteLine("File status  :{0}", m["Status"]);
    Console.WriteLine("File Type    :{0}", m["FileType"]);
    Console.WriteLine("Object Name  :" + m.ToString());

    Console.WriteLine("\nFile copying has been initiated ...");

    // Method - 1
    using (FileStream localDest = File.OpenWrite(localPath))
        using (FileStream remoteSource = File.OpenRead(remotePath))
        {
            remoteSource.CopyTo(localDest);
        }

    // Method - 2
    File.Copy(remotePath, localPath, true);

    // Method - 3
    inParams = m.GetMethodParameters("Copy");
    inParams["FileName"] = localPath;
    outParams = m.InvokeMethod("Copy", inParams, null);

    Console.WriteLine("Return value :" + outParams["ReturnValue"]);
    Console.WriteLine("\nFile copying completed !");
}

But the code is copying file from remote system to local system. I can able to make copies in the remote system, but cannot able to copy that to my local system

Your remote path looks like a UNC path.

\\\\REMOTESERVER\\SHARENAME\\Path\\to\\file.txt

Where SHARENAME is a shared folder. Windows automatically creates special admin shared folders for the drives on your machine with a $ suffix, so you have C$ mapping to the machines C: drive.

Your remote path should therefore be something like: \\\\RemoteComputer\\C$\\Folder1\\Testing\\Test.txt

You need admin rights on the remote machine to access such a share on a remote machine, or you can create named shares with custom permissions.

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