[英]How to transfer files to a shared folder using IP address in C#
我是 C# 的新手,我有一個 PowerShell 腳本可以使用 IP 地址和用戶名將文件發送到多台 PC,我正在使用 new-PSDrive。 我想在 C# 中創建相同的程序。
我不確定該怎么做,我瀏覽了一些教程並進行了嘗試,但仍然堅持使用 Windows Impersonate Class。 它寫在我關注的帖子中:_如果我們想將文件共享到共享文件夾,我們可以使用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(Username,Password);
我也試過這個 ("\192.xxx.xxx.xxx\WIN-9SMSBCR4V7B\SharedFolder",Password);
我要復制文件的機器正在同一台機器上的 Vmware 上運行,我可以使用 Powershell 腳本發送。
任何建議將不勝感激。
找到解決方案,這是使用 IP 地址、用戶名和密碼將文件發送到遠程 PC 的完整代碼,這些計算機不在同一域中。 這里的鏈接解釋了正確的 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);
}
}
}
希望這會對其他人有所幫助。
您可能認為將文件從一個文件夾復制到遠程共享(需要用戶名/密碼)會很簡單,但是,事實並非如此!
以下 2 個鏈接提供了一些選項:
上面的鏈接是關於先映射網絡驅動器然后進行文件復制
(2) 在c#中復制帶有身份驗證的文件
此選項與使用WindowsIdentity
類有關(正如您所嘗試的那樣)。 上面的鏈接提供了一種以正確方式構造對象的方法
在某種程度上,上述兩個選項都不是純 .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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.