我使用EventLogSession、EventLogQuery和EventLogReader类查询远程计算机,当我使用下面的代码时,它工作得很好:
var session = new EventLogSession(machineName,
null, null, null,
SessionAuthentication.Default);
但是,在我指定域、用户名、密码与我的本地机器完全相同之后,它就不工作了,抛出
“试图执行未经授权的操作”(UnauthorizedAccessException)异常。
我使用的代码如下:
var password = new SecureString();
passwordString.ToCharArray().ForEach(ch => password.AppendChar(ch));
var session = new EventLogSession(machineName,
"domain", "username", password,
SessionAuthentication.Default);
MSDN说,当域、用户名、密码都为空时,EventLogSession将使用本地机器的证书。但是当我在代码中指定它们时,它不起作用,怎么会这样呢?
顺便说一下,我正在使用Windows 2008 R2测试代码。但我怀疑这是不是一个依赖操作系统的东西。
Update:原来这是我的愚蠢造成的,因为我忘记了LINQ的懒惰,或者更确切地说是C#的返回。为方便起见,我按照以下扩展方法实现了ForEach
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
foreach (var item in sequence)
{
action(item);
yield return item;
}
}
这样,ForEach将不会实际执行操作委托,直到它被预先处理过为止。因此,我从不对char序列调用foreach,它永远不会执行,因此密码根本没有初始化。
抱歉打扰了你们,我把tammy的回答标记为接受了。
发布于 2013-01-10 05:49:43
http://msdn.microsoft.com/en-us/library/bb671200(v=vs.90).aspx
public void QueryRemoteComputer()
{
string queryString = "*[System/Level=2]"; // XPATH Query
SecureString pw = GetPassword();
EventLogSession session = new EventLogSession(
"RemoteComputerName", // Remote Computer
"Domain", // Domain
"Username", // Username
pw,
SessionAuthentication.Default);
pw.Dispose();
// Query the Application log on the remote computer.
EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
query.Session = session;
try
{
EventLogReader logReader = new EventLogReader(query);
// Display event info
DisplayEventAndLogInformation(logReader);
}
catch (EventLogException e)
{
Console.WriteLine("Could not query the remote computer! " + e.Message);
return;
}
}
https://stackoverflow.com/questions/14251356
复制相似问题