Class Program
{
Void Main () {
Copyfiletoediserver ("C:\Logs\NIS_20160930.log")
}
private void Copyfiletoediserver (string path)
{
Remoteinfo remote = new Remoteinfo ();
リモートサーバipaddress
Remote. Remoteip = "192.168.131.133";
リモートサーバユーザ Name
Remote. RemoteUser = "Administrator";
リモートサーバパスワード
Remote. Remotepwd = "s3300859!";
リモートサーバのshareフォルダ Name
Remote. ShareName = @ "\\192.168.131.133\pdf\";
String destinfile = remote. ShareName + fileupload1.filename;
using (identityscope c = new Identityscope (remote). REMOTEIP, remote. RemoteUser, remote. REMOTEPWD))
{
System.IO.File.Copy (path, destinfile);
}
}
}
public class Remoteinfo
{
public string Remoteip;
public string remotepwd;
public string RemoteUser;
public string ShareName;
public string Srcfilename;
public Remoteinfo ();
}
<summary>
Identityscope
</summary>
public class Identityscope:idisposable
{
Obtains user Token
[DllImport ("advapi32.dll", SetLastError = True)]
static extern bool LogonUser (
String Pszusername,
String Pszdomain,
String Pszpassword,
int dwLogonType,
int dwLogonProvider,
Ref INTPTR Phtoken);
Closes open Handes returned by LogonUser
[DllImport ("kernel32.dll", CharSet = CharSet.Auto)]
extern static bool CloseHandle (INTPTR handle);
[DllImport ("Advapi32.DLL")]
static extern bool ImpersonateLoggedOnUser (IntPtr htoken);
[DllImport ("Advapi32.DLL")]
static extern bool RevertToSelf ();
const int logon32_provider_default = 0;
const int logon32_logon_newcredentials = 9;
private bool disposed;
Public Identityscope (String sdomain, String sUserName, String spassword)
{
Initialize Tokens
IntPtr pexistingtokenhandle = new IntPtr (0);
IntPtr pduplicatetokenhandle = new IntPtr (0);
Try
{
Get handle to Token
BOOL bimpersonated = LogonUser (sUserName, Sdomain, Spassword,
Logon32_logon_newcredentials, Logon32_provider_default, ref pexistingtokenhandle);
if (true = = bimpersonated)
{
if (! ImpersonateLoggedOnUser (Pexistingtokenhandle))
{
int nerrorcode = Marshal.GetLastWin32Error ();
throw new Exception ("ImpersonateLoggedOnUser error; Code= "+ nerrorcode);
}
}
Else
{
int nerrorcode = Marshal.GetLastWin32Error ();
throw new Exception ("LogonUser error; Code= "+ nerrorcode);
}
}
Finally
{
Close handle (s)
if (pexistingtokenhandle! = IntPtr.Zero)
{
CloseHandle (Pexistingtokenhandle);
}
if (pduplicatetokenhandle! = IntPtr.Zero)
{
CloseHandle (Pduplicatetokenhandle);
}
}
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
RevertToSelf ();
disposed = true;
}
}
public void Dispose ()
{
Dispose (TRUE);
}
}
Simple example of remote file copying in C #