如何在C#中使用IP地址将文件传输到共享文件夹

How to transfer files to a shared folder using IP address in C#

我是 C# 的新手,我有一个 PowerShell 脚本可以使用 IP 地址和用户名将文件发送到多台 PC,我正在使用 new-PSDrive。我想在 C# 中创建相同的程序。

我不确定该怎么做,我浏览了一些教程并进行了尝试,但仍然坚持使用 Windows 模拟 Class。它写在 post 中,我遵循了:_如果我们想将文件共享到共享文件夹,我们可以使用 File.Copy(destPath, SourcePath) 但它不工作。

这是我正在尝试的代码:

WindowsIdentity idnt = new WindowsIdentity("Administrator", "Test123!");
WindowsImpersonationContext context = idnt.Impersonate();
File.Copy(@"C:\Sent.txt", @"\192.xxx.xxx.xxx\SharedFolder", true);
context.Undo(); 

弹出错误消息:提供的名称不是正确格式的帐户名称。 WindowsIdentity idnt = new WindowsIdentity("Administrator", "Test123!");

我不知道如何获得正确的名称,我正在尝试这样做: WindowsIdentity idnt = new WindowsIdentity(用户名,密码);

我也试过这个 ("\192.xxx.xxx.xxx\WIN-9SMSBCR4V7B\SharedFolder",Password);

我要复制文件的机器 运行 在同一台机器上的 Vmware 上,我可以使用 Powershell 脚本发送。

如有任何建议,我们将不胜感激。

您可能会认为将文件从一个文件夹复制到远程共享(需要用户名/密码)会很简单!但是,它不是!

以下 2 link 提供了一些选项:

(1) How to provide user name and password when connecting to a network share

以上link是先映射网盘再做文件拷贝

(2) copy files with authentication in c#

此选项是关于使用 WindowsIdentity class(如您所试)。上面link给出了正确构造对象的方法

从某种意义上说,上述两个选项都不是纯 .Net 解决方案。他们直接调用 Win32 API。

另一个选项:

如果您可以先创建一个映射网络连接(在您的应用程序外部),那么简单的文件复制就可以了。

在这种情况下,步骤为:

(1) 使用用户名和密码将驱动器映射到共享文件夹,使用 net use 命令

net use Z: /delete
net use Z: \server name\share name password /user:user name

(2) 运行 你的复制程序

File.Copy(sourceFileName, @"Z:\path\to\folder\filename");

(3) 删除驱动器映射

net use Z: /delete

找到解决方案,这是使用 IP 地址、用户名和密码将文件发送到远程 PC 的完整代码,这些计算机不在同一域中。 Here the Link which explains the use of correct LOGON PROVIDER

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.IO;

namespace File_Send_Test
{
    class Program
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
         int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        // Test harness.
        // If you incorporate this code into a DLL, be sure to demand FullTrust.
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        public static void Main(string[] args)
        {
            SafeTokenHandle safeTokenHandle;
            try
            {
                string userName, domainName;
                //domainName = Console.ReadLine();
                domainName = ".";

                Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
                //provide username of remote machine.
                userName = Console.ReadLine();
                //provide password of remote machine.
                Console.Write("Enter the password for {0}: ", userName);

                //Here's the Catch 
                //LOGON32_PROVIDER_WinNT50 = 3; and LOGON32_LOGON_NewCredentials = 9;
                const int LOGON32_PROVIDER_WinNT50 = 3;
                //This parameter causes LogonUser to create a primary token.
                const int LOGON32_LOGON_NewCredentials = 9;

                // Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
                    LOGON32_LOGON_NewCredentials, LOGON32_PROVIDER_WinNT50,
                    out safeTokenHandle);

                Console.WriteLine("LogonUser called.");

                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser failed with error code : {0}", ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                using (safeTokenHandle)
                {
                    Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                    Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);

                    // Check the identity.
                    Console.WriteLine("Before impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
                    // Use the token handle returned by LogonUser.
                    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {

                            // Check the identity.
                            Console.WriteLine("After impersonation: "
                                + WindowsIdentity.GetCurrent().Name);
                            //File.Copy(Source File,DestinationFile);
                            File.Copy(@"C:\Sent.txt", @"\192.168.xxx.xxx\Suji\Sent.txt", true);
                        }
                    }
                    // Releasing the context object stops the impersonation
                    // Check the identity.
                    Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred. " + ex.Message);
            }
            Console.ReadLine();
        }
    }
    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

希望这对其他人有帮助。