現在ログインしているユーザーからデフォルトの資格情報を取得し、Windowsサービスに渡してインターネット接続を確認し、Dropboxにファイルをアップロードする必要があります。私は、ユーザーが毎回自分の資格情報を確認しないようにします。では、現在アクティブなユーザのプロキシ設定+ユーザ名+パスワードを取得するにはどうすればよいですか?WebcredentialsをアクティブユーザーからWindowsサービスに渡す方法
これは、現在のユーザー
private static string UserName()
{
string userName = null;
ManagementScope ms = new ManagementScope();
ObjectQuery qry = new ObjectQuery("Select * from Win32_ComputerSystem");
ManagementObjectSearcher search = new ManagementObjectSearcher(ms, qry);
ManagementObjectCollection result = search.Get();
foreach (ManagementObject rec in result)
userName = rec["UserName"] as string;
string[] buffer = userName.Split('\\');
return buffer[1];
}
を取得するために私のコードであり、このコードは、WindowsIdentityを取得するために使用している:
private static WindowsIdentity GetWindowsIdentity()
{
string userName = UserName();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName) ??
UserPrincipal.FindByIdentity(UserPrincipal.Current.Context, IdentityType.UserPrincipalName, userName))
{
return user == null
? null
: new WindowsIdentity(user.UserPrincipalName);
}
}
これは私がサービスを介して何をしたいです:
System.Diagnostics.Debugger.Launch(); //launch debugger when service runs
WindowsImpersonationContext impersonationContext;
impersonationContext = GetWindowsIdentity().Impersonate();
//try to use the currently logged in user's credentials
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
try
{
WebClient wClient = new WebClient();
string xx = wClient.DownloadString(@"https://dropbox.com");
if (xx == "") //just download the sourcecode to chek if this page is available
return false;
}
catch (Exception ex)
{
using (StreamWriter sw = new StreamWriter(@"C:\Users\Testuser\Desktop\DownloadError.txt", true))
{
sw.WriteLine(ex.ToString());
}
return false;
}
impersonationContext.Undo();
エラーログには、サービスが接続できなかったことが常に示されます。これをコンソールやWinFormsアプリケーションから実行すると、問題なく動作します。
エラーログ:
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 172.217.17.238:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at BeeShotService.Sender.TrySend(String s) in C:\Users\Testuser\Documents\Visual Studio 2017\Projects\Project_BackupUploder\UploaderService\Sender.cs:Zeile 70.