You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#凭借IP地址与凭据实现本地到远程机器的文件复制

Hey there! Let's walk through how to implement copying files from your local machine to a remote server using C#, where you'll authenticate with the server's IP address and credentials. I'll cover two practical, widely-used approaches depending on your server's operating system:


Approach 1: SMB File Transfer (For Windows Servers)

If you're targeting a Windows server, you can leverage the SMB protocol to map a network share and transfer files just like you would with local files. To handle authentication, we'll use the Windows API's WNetAddConnection2 method to establish a secure connection first.

Step-by-Step Implementation

  1. Declare the Windows API imports (required to handle network connections):
using System;
using System.IO;
using System.Runtime.InteropServices;

public class SmbFileTransfer
{
    [StructLayout(LayoutKind.Sequential)]
    private struct NETRESOURCE
    {
        public int dwScope;
        public int dwType;
        public int dwDisplayType;
        public int dwUsage;
        public string lpLocalName;
        public string lpRemoteName;
        public string lpComment;
        public string lpProvider;
    }

    [DllImport("mpr.dll")]
    private static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUserName, int dwFlags);

    [DllImport("mpr.dll")]
    private static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);
  1. Establish connection and transfer the file:
public static void CopyFileToRemoteSmb(string serverIp, string shareName, string username, string password, string localFilePath, string remoteFilePath)
    {
        var netResource = new NETRESOURCE
        {
            dwType = 0x00000001, // RESOURCETYPE_DISK
            lpRemoteName = $"\\\\{serverIp}\\{shareName}"
        };

        // Connect to the remote share
        int connectionResult = WNetAddConnection2(ref netResource, password, username, 0);
        if (connectionResult != 0)
        {
            throw new Exception($"Failed to connect to remote share. Error code: {connectionResult}");
        }

        try
        {
            // Combine the share path with the remote file path
            string fullRemotePath = Path.Combine($"\\\\{serverIp}\\{shareName}", remoteFilePath);
            // Ensure the remote directory exists
            Directory.CreateDirectory(Path.GetDirectoryName(fullRemotePath));
            // Copy the file
            File.Copy(localFilePath, fullRemotePath, overwrite: true);
            Console.WriteLine("File copied successfully via SMB!");
        }
        finally
        {
            // Always disconnect to clean up resources
            WNetCancelConnection2($"\\\\{serverIp}\\{shareName}", 0, true);
        }
    }
}
  1. Usage Example:
SmbFileTransfer.CopyFileToRemoteSmb(
    serverIp: "192.168.1.100",
    shareName: "SharedFiles",
    username: "remoteUser",
    password: "securePassword123",
    localFilePath: @"C:\LocalFiles\document.pdf",
    remoteFilePath: "ReceivedFiles\document.pdf"
);

Approach 2: SSH/SCP File Transfer (Cross-Platform)

For cross-platform scenarios (e.g., Linux servers, or Windows with SSH enabled), using SCP over SSH is a reliable choice. We'll use the SSH.NET library, a popular open-source package for SSH operations in C#.

Step-by-Step Implementation

  1. Install the SSH.NET NuGet Package:
    Open your NuGet Package Manager and run:
Install-Package SSH.NET

Or via .NET CLI:

dotnet add package SSH.NET
  1. Implement the SCP File Upload:
using Renci.SshNet;
using System.IO;

public class ScpFileTransfer
{
    public static void UploadFileViaScp(string serverIp, int port, string username, string password, string localFilePath, string remoteFilePath)
    {
        // Set up SSH client credentials
        var credentials = new PasswordAuthenticationMethod(username, password);
        var connectionInfo = new ConnectionInfo(serverIp, port, credentials);

        using (var sshClient = new SshClient(connectionInfo))
        using (var scpClient = new ScpClient(connectionInfo))
        {
            sshClient.Connect();
            scpClient.Connect();

            try
            {
                // Upload the local file to the remote server
                using (var fileStream = new FileStream(localFilePath, FileMode.Open))
                {
                    scpClient.Upload(fileStream, remoteFilePath);
                }
                Console.WriteLine("File uploaded successfully via SCP!");
            }
            finally
            {
                scpClient.Disconnect();
                sshClient.Disconnect();
            }
        }
    }
}
  1. Usage Example:
ScpFileTransfer.UploadFileViaScp(
    serverIp: "192.168.1.101",
    port: 22, // Default SSH port
    username: "linuxUser",
    password: "securePass456",
    localFilePath: @"C:\LocalFiles\data.zip",
    remoteFilePath: "/home/linuxUser/uploads/data.zip"
);

Important Notes

  • Security: Never hardcode credentials in your code! Use secure storage (like environment variables, encrypted config files, or credential managers) and convert passwords to SecureString where possible.
  • Firewall Permissions: Ensure the remote server's firewall allows the required ports:
    • SMB: Port 445
    • SSH/SCP: Port 22
  • Permissions: Verify the provided user account has write access to the target remote directory/share.

内容的提问来源于stack exchange,提问作者kheph_1992

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:19:47