Dan*_*Edw 3 c# filesystems c#-4.0
我正在尝试使用由加密的.config文件提供的有限管理员帐户的凭据创建文件夹 - 现在我的代码在假设用户无法访问这些目录的情况下运行,因此在给定时会抛出unauthorizedexception访问代码否则有效,但我不能这样做,因为它会危及我们的安全.我知道如何从加密文件中取出我的用户名/密码,我只是不确定我应该用什么库或语法来模仿; 这是我的代码:
//set the cursor
string activeDir = "\\\\department\\shares\\users\\";
//create directory with userID as the folder name
string newPath = System.IO.Path.Combine(activeDir + userID);
System.IO.Directory.CreateDirectory(newPath);
Run Code Online (Sandbox Code Playgroud)
所以我需要一种方法来提供凭证,但我不知所措 - 我一直在使用System.DirectoryServices.AccountManagement和pricipalcontext提供用户名/密码来更改活动目录...我需要使用一个类似的库来更改文件系统?任何帮助将不胜感激,谢谢!
我认为您可以临时模拟执行此操作的线程的用户.似乎这只能通过P/Invoke来完成.看看这个例子.
using (var impersonation = new ImpersonatedUser(decryptedUser, decryptedDomain, decryptedPassword))
{
Directory.CreateDirectory(newPath);
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见(如果某天链接停止工作),请找到ImpersonatedUser下面的课程(Jon Cole学分):
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class ImpersonatedUser : IDisposable
{
IntPtr userHandle;
WindowsImpersonationContext impersonationContext;
public ImpersonatedUser(string user, string domain, string password)
{
userHandle = IntPtr.Zero;
bool loggedOn = LogonUser(
user,
domain,
password,
LogonType.Interactive,
LogonProvider.Default,
out userHandle);
if (!loggedOn)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate(userHandle);
}
public void Dispose()
{
if (userHandle != IntPtr.Zero)
{
CloseHandle(userHandle);
userHandle = IntPtr.Zero;
impersonationContext.Undo();
}
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
LogonType dwLogonType,
LogonProvider dwLogonProvider,
out IntPtr phToken
);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hHandle);
enum LogonType : int
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
NetworkCleartext = 8,
NewCredentials = 9,
}
enum LogonProvider : int
{
Default = 0,
}
}
Run Code Online (Sandbox Code Playgroud)