i found a piece of code which is written in console application and also working. here is the code..
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
Console.WriteLine("Process: {0} ID :{1} Window Title :{2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
and i have modified the code like this...
StreamWriter str = new StreamWriter("D:\\loop.txt", true);
str.WriteLine("**** List of Application *********");
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
str.WriteLine("Process: {0} ID :{1} Window Title :{2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
str.close();
but it is not working in windows service. Did i made a mistake? i am new to windows service . is there any one can help me? what should i do?
You have forgot to Close the stream
Quoted:
You must call Close to ensure that all data is correctly written out to the underlying stream. Following a call to Close, any operations on the StreamWriter might raise exceptions. If there is insufficient space on the disk, calling Close will raise an exception.
Corrected code :
StreamWriter str = new StreamWriter("D:\\loop.txt", true);
str.WriteLine("**** List of Application *********");
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
str.WriteLine("Process: {0} ID :{1} Window Title :{2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
str.Close(); // You need to close the stream
Alternative : Using
using (StreamWriter str = new StreamWriter("D:\\loop.txt", true))
{
str.WriteLine("**** List of Application *********");
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
str.WriteLine("Process: {0} ID :{1} Window Title :{2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.