我有一些代码可以使用在客户端计算机上运行的服务在网络上删除用户配置文件,如下所示:
public static void DeleteProfiles()
{
ConsoleWrapper.WriteLine("We're in DeleteProfiles()");
try
{
string[] users = GetUsers();
ConsoleWrapper.WriteLine("Users gotten");
if (users == null || users.Length == 0)
{
DeletingProfiles = false;
ConsoleWrapper.WriteLine("Null or no user loaded");
return;
}
DirectoryInfo oInfo = new DirectoryInfo("C:/Users");
if (!oInfo.Exists)
oInfo = new DirectoryInfo("C:/Documents and Settings");
ConsoleWrapper.WriteLine("Profile folder gotten.");
ConsoleWrapper.WriteLine("User Directory: " + oInfo.FullName);
ConsoleWrapper.WriteLine("\nDirectories to be deleted:");
DirectoryInfo[] SubDirectories = oInfo.GetDirectories();
foreach (DirectoryInfo oSubDir in SubDirectories)
{
bool match = false;
foreach (string user in users)
{
if (user == null)
continue;
if (oSubDir.Name.ToLower() == user.ToLower())
{
ConsoleWrapper.WriteLine("Matched: " + oSubDir.FullName);
match = true;
break;
}
}
if (match)
continue;
try
{
ConsoleWrapper.WriteLine(oSubDir.FullName);
DeletePath(oSubDir.FullName);
}
catch (Exception ex)
{
ConsoleWrapper.WriteLine(ex.StackTrace);
}
}
}
catch (Exception dirEx)
{
ConsoleWrapper.WriteLine(dirEx.Message);
}
}
ConsoleWrapper中的WriteLine方法实际上将数据附加到txt文件,因为这是我能想到在不同机器上调试的最简单方法。
当我在命令行应用程序中使用它时,这个确切的代码有效,但当我尝试在Windows服务中使用它时,它只是写“我们在DeleteProfiles()中。”正如你会注意到的那样,我已经抓住了所有“可捕捉”的异常,但我仍然不明白发生了什么。
所有客户端计算机都出现此问题,但它在我的台式机和笔记本电脑上运行良好。我做错了什么?
有关DeletePath代码,请参阅http://www.vbdotnetforums.com/windows-services/16909-deletedirectory-throws-exception.html#post51470。我几乎解除了它并将其转换为C#代码。
答案 0 :(得分:2)
如果您发现了每个可捕获的异常并且您没有在日志中看到条目,则很可能会抛出不可捕获的异常。这通常采用StackOverflowException的形式。默认情况下,进程无法捕获此类异常。
如果DeletePath是一个递归函数,请尝试迭代,看看是否能解决问题。
答案 1 :(得分:2)
你可能没有刷新ConsoleWrapper。尝试在最后一个块中放入一个刷新,或者打开autoflush。
答案 2 :(得分:2)
GetUsers()做什么?
可能需要很长时间吗?
您是如何从服务中调用DeleteProfiles()的?
如果直接从ServiceBase.OnStart()的覆盖调用DeleteProfiles(),则需要知道OnStart()在30秒后超时。
答案 3 :(得分:2)
服务需要额外的证券才能与桌面交互。有一个安装程序可以在这里为您提供: http://www.codeproject.com/KB/install/cswindowsservicedesktop.aspx
答案 4 :(得分:1)
如果您无法弄明白,请将remote debugging monitor放在客户端上并附加到该客户端。您可能必须在方法之上放置一个Thread.Sleep(),以便您有足够的时间在客户端的进程列表中查找服务进程,并在实际运行时附加它。
答案 5 :(得分:0)
从日志记录的角度来看,我会使用一个众所周知的库,如log4net或Microsoft的Logging Application Block。滚动自己的日志记录时,请确保调用Flush()以清除任何缓冲区写入。我发现log4net更容易合并到现有代码中,除非您已经是企业库商店。