摘要:[.net]程式碼如何寫入網芳、網路磁碟、網路硬碟
1.首先設定要分享的目錄的安全性以及共用性,先從安全性開始
要讓本機iis可用程式碼存取的話,就加入本機的IIS_IUSER,NETWORK,NETWORK_SERVICE的帳號,並給予完全控制權限
要讓外部主機可用程式碼存取的話,就在控制台開個帳號給他,並加入此帳號的完全控制權限,某某主機到時候就用這個帳號存取此資料夾
然後設定共用:剛剛在安全性加入哪個帳號,你就在這邊加入哪個帳號
加入成功之後顯示的結果如下:會顯示這個資料夾的完整共用路徑:\\網域\資料夾名稱
2.然後利用網路上寫好的impersonator.cs,傳入登入帳號密碼,就可以用這個class來登入網路磁碟
貼在程式碼文字編輯器裡面的話,格式會整個跑掉,所以純文字貼上
如果在上一步驟,只是要給本機iis存取資料夾,不是給某某主機存取的話,本步驟可省略
直接就可以在程式碼中用File.Copy,File.Delete去存取此網路硬碟
namespace MyProject
{
#region Using directives.
// ----------------------------------------------------------------------
using System;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.ComponentModel;
// ----------------------------------------------------------------------
#endregion
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Impersonation of a user. Allows to execute code under another
/// user context.
/// Please note that the account that instantiates the Impersonator class
/// needs to have the 'Act as part of operating system' privilege set.
/// </summary>
/// <remarks>
/// This class is based on the information in the Microsoft knowledge base
/// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158
///
/// Encapsulate an instance into a using-directive like e.g.:
///
/// ...
/// using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
/// {
/// ...
/// [code that executes under the new context]
/// ...
/// }
/// ...
///
/// Please contact the author Uwe Keim (mailto:uwe.keim@zeta-software.de)
/// for questions regarding this class.
/// </remarks>
public class Impersonator :
IDisposable
{
#region Public methods.
// ------------------------------------------------------------------
/// <summary>
/// Constructor. Starts the impersonation with the given credentials.
/// Please note that the account that instantiates the Impersonator class
/// needs to have the 'Act as part of operating system' privilege set.
/// </summary>
/// <param name="userName">The name of the user to act as.</param>
/// <param name="domainName">The domain name of the user to act as.</param>
/// <param name="password">The password of the user to act as.</param>
public Impersonator(
string userName,
string domainName,
string password)
{
ImpersonateValidUser(userName, domainName, password);
}
// ------------------------------------------------------------------
#endregion
#region IDisposable member.
// ------------------------------------------------------------------
public void Dispose()
{
UndoImpersonation();
}
// ------------------------------------------------------------------
#endregion
#region P/Invoke.
// ------------------------------------------------------------------
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int LogonUser(
string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(
IntPtr handle);
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private const int LOGON32_LOGON_NETWORK = 3;
private const int LOGON32_LOGON_BATCH = 4;
private const int LOGON32_LOGON_SERVICE = 5;
private const int LOGON32_LOGON_UNLOCK = 7;
private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8; // Only for Win2K or higher
private const int LOGON32_LOGON_NEW_CREDENTIALS = 9; // Only for Win2K or higher
// ------------------------------------------------------------------
#endregion
#region Private member.
// ------------------------------------------------------------------
/// <summary>
/// Does the actual impersonation.
/// </summary>
/// <param name="userName">The name of the user to act as.</param>
/// <param name="domainName">The domain name of the user to act as.</param>
/// <param name="password">The password of the user to act as.</param>
private void ImpersonateValidUser(
string userName,
string domain,
string password)
{
WindowsIdentity tempWindowsIdentity = null;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
try
{
if (RevertToSelf())
{//LOGON32_LOGON_NETWORK_CLEARTEXT通常是在Server為了配合多平台的檔案寫入(例如:linux)
//才會用這個降低安全性的選項,讓server允許直接帳號密碼登入並且寫入檔案系統
//LOGON32_LOGON_NEW_CREDENTIALS才是一般server會採用的安全性作法,使用者需利用帳密取得一組credential
//再用credential去登入server, 方可寫入server的檔案系統
//完整的LogonType解釋詳見msdn
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
//Server的這個設定在 程式集=>系統管理工具=>本機安全性原則裡面,此設定為進階設定,非mis人員通常很少設定他
if (LogonUser(
userName,
domain,
password,
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT,
ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
}
}
/// <summary>
/// Reverts the impersonation.
/// </summary>
private void UndoImpersonation()
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
private WindowsImpersonationContext impersonationContext = null;
// ------------------------------------------------------------------
#endregion
}
/////////////////////////////////////////////////////////////////////////
}
3.最後在程式碼中,只要利用using (Impersonator.....),就可以用程式碼直接存取此網路硬碟了
新增編輯刪除修改檔案等動作
using (new Impersonator("yourUserName", "yourDomainName","yourPassword"))
{
if (!Directory.Exists(remotePath)) Directory.CreateDirectory(remotePath);
File.Copy(localFile, remoteFile, true);
}