C# 复制文件本地到远程或远程到本地

C# Copy file local to remote or remote to local

我有自定义组件 SSIS,我需要将文件从本地复制到远程或从远程复制到本地,但我的远程地址使用凭据。

如果我从远程凭据位置复制,它有效,但相反,它不起作用。

有没有更好的选择?

从远程复制到本地:

using (new NetworkConnection(folder, new NetworkCredential(userName, password, domain)))
                    {
                        if (isCreateDirectoryDestination)
                        {
                            if (!Directory.Exists(Path.GetDirectoryName(fileDestination)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(fileDestination));
                            }
                        }

                        File.Copy(fileSource, fileDestination, isOverwrite);
                    }

将文件从本地复制到远程

if (isCreateDirectoryDestination)
                {
                    if (!Directory.Exists(Path.GetDirectoryName(fileDestination)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(fileDestination));
                    }
                }

                File.Copy(fileSource, fileDestination, isOverwrite);

您需要使用模拟

IntPtr tokenHandle = new IntPtr(0);  
tokenHandle = IntPtr.Zero;  

bool returnValue = LogonUser(<userName>, <domain>, <password>, 2, 0, ref tokenHandle);  
WindowsIdentity ImpersonatedIdentity = new WindowsIdentity(tokenHandle);  
WindowsImpersonationContext MyImpersonation = ImpersonatedIdentity.Impersonate();