Jose Jose - 7 months ago 38
C# Question

My custom Windows Service not working with Windows Message Queue

The windows service i coded is not working:

  • Intended funcionality: The service is supposed to receive messages from Windows Message Queue (MSMQ) and write the messages on .txt files.

  • It works when I run it not-as-a-service (directly from visual studio)

  • When I installed it as a service i can start it, but it doesn't do anything, not creating/writing .txt files anywhere

(I know it isn't writing the files elsewhere because when I run the program from VS the messages are still in the queue, so they weren't taken out by the service)

The difference between running it as a service and running it from visual studio is the next:

namespace ComponentAtrapador
static class Program
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
Service1 myService = new Service1();

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
new Service1()

(so if i run it as DEBUG it will run without me having to install it as a service)

Here's the service's code:

namespace ComponentAtrapador
public partial class Service1 : ServiceBase
private System.Timers.Timer _timer;
private System.ComponentModel.IContainer components1;
private System.Diagnostics.EventLog eventLog1;

public void startMethod()
public Service1()
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
"MySource", "MyNewLog");
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";

protected override void OnStart(string[] args)
eventLog1.WriteEntry("In OnStart");
_timer = new System.Timers.Timer();
_timer.Interval = 5000; // 5 seconds
_timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);

protected override void OnStop()

public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
string nombreArchivo = "archivoMensaje";
MessageQueue messageQueue = new MessageQueue(@".\Private$\SomeTestName");
System.Messaging.Message[] messages = messageQueue.GetAllMessages();

System.Messaging.Message m = new System.Messaging.Message();
foreach (System.Messaging.Message message in messages)
message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
string text = message.Body.ToString();
System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + nombreArchivo + Properties.Settings.Default.SettingNumero + ".txt", text);
//Do something with the message.
// after all processing, delete all the messages




Turns out the service didn't have enough permissions, fixed it by setting the serviceProcessInstaller of the service on visual studio to User, so that when i installed it it'd ask for credentials. Just had to type "./[username]" when it asked for my username for it to work.

Another way of fixing it would be going into the task manager > services > right click service > properties > security. And change the permissions there.