Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7562701
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T13:28:32+00:00 2026-05-30T13:28:32+00:00

I have a c# app (Windows Service) that fires a timer event that reads

  • 0

I have a c# app (Windows Service) that fires a timer event that reads files in a directory and sends out SMS using the data in the files. Next time the event fires, it tries to move the processed files in the “Processed” directory to a “Completed” directory before processing the new files. I keep getting a “File in use by another process” exception, although I am pretty sure that I dispose of everything that uses the files. If I stop the service and start it again, the files is released. Any ideas?

//Code that fires the timer    
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;

namespace SmsWindowsService
{
    public partial class SmsWindowsService : ServiceBase
    {
        private static System.Timers.Timer aTimer;

        public SmsWindowsService()
        {
            InitializeComponent();

            if (!System.Diagnostics.EventLog.SourceExists("MatterCentreSMSSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "MatterCentreSMSSource", "MatterCentreSMSLog");
            }
            elMatterCentreSMS.Source = "MatterCentreSMSSource";
            elMatterCentreSMS.Log = "MatterCentreSMSLog";

        }

        protected override void OnStart(string[] args)
        {
            string logText = string.Empty;

            logText = "MatterCentreSMS Service started successfully on " + DateTime.Now;

            WriteEventLog(logText);

            //Create a timer with a ten second interval.
            aTimer = new System.Timers.Timer(10000);

            //Hook up the Elapsed event for the timer.
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

            //Set the Interval to 5 minutes.
            //aTimer.Interval = 300000;
            aTimer.Interval = 60000;
            aTimer.Enabled = true;

            // If the timer is declared in a long-running method, use
            // KeepAlive to prevent garbage collection from occurring
            // before the method ends.
            //GC.KeepAlive(aTimer);
            GC.Collect();
        }

        protected override void OnStop()
        {
            string logText = string.Empty;

            logText = "MatterCentreSMS Service stopped on " + DateTime.Now;

            WriteEventLog(logText);
        }

        private void WriteEventLog(string logText)
        {
            elMatterCentreSMS.WriteEntry(logText);
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            string ex = string.Empty;

            SendSms s = new SendSms();

            ex = s.ProcessSms();

            if (ex.Length > 1)
                WriteEventLog(ex);

            //ex = RestartService("SmsWindowsService", 60000);
            //WriteEventLog(ex);
        }

        public string RestartService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);

            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);

                return "MatterCentreSMS Service successfully restarted on " + DateTime.Now;
            }

            catch (Exception e)
            {
                return Convert.ToString(e);
            }
        }
    }
}

//Code that reads the file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace SmsWindowsService
{
    class Message
    {
        private string filePath;

        public Message(string filePath)
        {
            this.filePath = filePath;
        }

        public string readSMS(string filePath)
        {
            const string searchmessage = "[B-->]";
            StreamReader smsmessage = new StreamReader(filePath);

            try
            {
                FileInfo filenameinfo = new FileInfo(filePath);
                if (filenameinfo.Exists == false)
                    throw new SMSReaderException(String.Format("SMS Message {0} cannot be found ...", filePath), filePath);

                smsmessage = filenameinfo.OpenText();
                string smsoutput = smsmessage.ReadToEnd();
                int endpos = smsoutput.IndexOf(searchmessage);
                smsoutput = smsoutput.Substring(endpos + searchmessage.Length);
                smsoutput = smsoutput.Replace("&", "&");
                smsoutput = smsoutput.Replace("\"", """);
                smsoutput = smsoutput.Replace("'", "'");

                filenameinfo = null;
                smsmessage.Close();
                smsmessage.Dispose();

                return smsoutput;
            }

            catch(Exception e)
            {
                throw new Exception("Help", e.InnerException);
            }

            finally
            {
                smsmessage.Close();
                smsmessage.Dispose();
            }
        }
    }

    public class SMSReaderException : System.IO.FileNotFoundException
    {
        public SMSReaderException(string message, string filename)
            : base(message, filename)
        {
        }
    }
    }

//Code that connects to web service and send sms
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Net;
using System.Configuration;
using SmsWindowsService.EsendexSendSmsService;

namespace SmsWindowsService
{
    class SendSms
    {
        string filePath = string.Empty;
        string directoryPath = string.Empty;
        string directoryPathProcessing = string.Empty;
        string directoryPathCompleted = string.Empty;
        string smsLogfileDirectory = string.Empty;
        string smsLogfilePath = string.Empty;
        string mattercentreSMS = string.Empty;
        string messageBody = string.Empty;
        string messageId = string.Empty;
        string messageStatus = string.Empty;
        string dateTodayString = string.Empty;
        long mobileNumber;
        EsendexSendSmsService.SendService send;

        public SendSms()
        {
            directoryPath = ConfigurationSettings.AppSettings[@"directoryPath"];
            directoryPathProcessing = ConfigurationSettings.AppSettings[@"directoryPathProcessing"];
            directoryPathCompleted = ConfigurationSettings.AppSettings[@"directoryPathCompleted"];
            smsLogfileDirectory = ConfigurationSettings.AppSettings[@"smsLogfileDirectory"];            
            dateTodayString = DateTime.Now.ToString("yyyy/MM/dd");
            smsLogfilePath = smsLogfileDirectory + dateTodayString.Replace(@"/", "_") + ".txt";
            send = new EsendexSendSmsService.SendService();
        }

        public string ProcessSms()
        {
            string ex = string.Empty;

            try
            {
                DirectoryInfo di = new DirectoryInfo(directoryPathProcessing);

                ex = MoveFilesToCompleted(directoryPathProcessing, directoryPathCompleted);

                if (ex.Length > 1)
                    return ex;

                ex = MoveFilesToProcessing(directoryPath, directoryPathProcessing);

                if (ex.Length > 1)
                    return ex;

                FileInfo[] subFilesProcessing = di.GetFiles();

                foreach (FileInfo subFile in subFilesProcessing)
                {
                    filePath = directoryPathProcessing + subFile.Name;

                    Message sms = new Message(filePath);

                    mattercentreSMS = sms.readSMS(filePath);

                    MessageDetails d = new MessageDetails(mattercentreSMS);

                    mobileNumber = d.GetMobileNumber();
                    messageBody = d.GetMessageBody();

                    ex = SetHeader();

                    if (ex.Length > 1)
                        return ex;

                    ex = SetProxy();

                    if (ex.Length > 1)
                        return ex;

                    //Send the message and get the returned messageID and send status
                    messageId = send.SendMessage(Convert.ToString(mobileNumber), messageBody, EsendexSendSmsService.MessageType.Text);
                    messageStatus = Convert.ToString(send.GetMessageStatus(messageId));

                    ex = WriteLogFile(messageId, subFile.Name, messageStatus);

                    if (ex.Length > 1)
                        return ex;

                    send.Dispose();
                }

                di = null;
                subFilesProcessing = null;

                return ex;
            }

            catch (Exception e)
            {
                return Convert.ToString(e);
            }
        }

        private string MoveFilesToCompleted(string directoryPathProcessing, string directoryPathCompleted)
        {
            DirectoryInfo din = new DirectoryInfo(directoryPathProcessing);

            try
            {                
                FileInfo[] subFiles = din.GetFiles();

                foreach (FileInfo subFile in subFiles)
                {
                    subFile.MoveTo(directoryPathCompleted + subFile.Name);
                }

                subFiles = null;
                return "";                
            }

            catch (Exception e)
            {
                return Convert.ToString(e);
            }

            finally
            {
                din = null;
            }
        }

        private string MoveFilesToProcessing(string directoryPath, string directoryPathProcessing)
        {
            DirectoryInfo din = new DirectoryInfo(directoryPath);

            try
            {
                FileInfo[] subFiles = din.GetFiles();

                foreach (FileInfo subFile in subFiles)
                {
                    subFile.MoveTo(directoryPathProcessing + subFile.Name);
                }

                subFiles = null;
                return "";
            }

            catch (Exception e)
            {
                return Convert.ToString(e);
            }

            finally
            {
                din = null;
            }
        }

        private string SetHeader()
        {
            try
            {
                //Setup account details in the header
                EsendexSendSmsService.MessengerHeader header = new EsendexSendSmsService.MessengerHeader();
                header.Account = ConfigurationSettings.AppSettings[@"smsServiceUrl"];
                header.Username = ConfigurationSettings.AppSettings[@"smsServiceUsername"];
                header.Password = ConfigurationSettings.AppSettings[@"smsServicePassword"];

                // set the SOAP header Authentication values
                send.MessengerHeaderValue = header;

                return "";
            }

            catch (Exception e)
            {
                return Convert.ToString(e);
            }
        }

        private string SetProxy()
        {
            try
            {
                //Create a web proxy object as the proxy server block direct request to esendex 
                WebProxy myProxy = new WebProxy(ConfigurationSettings.AppSettings[@"proxyaddress"], true);
                myProxy.Credentials = new NetworkCredential(ConfigurationSettings.AppSettings[@"username"], ConfigurationSettings.AppSettings[@"password"]);
                WebRequest.DefaultWebProxy = myProxy;
                send.Proxy = myProxy;

                return "";
            }

            catch (Exception e)
            {
                return Convert.ToString(e);
            }
        }

        private string WriteLogFile(string messageId, string smsFileName, string messageStatus)
        {
            try
            {
                if (File.Exists(smsLogfilePath))
                {
                    //file is not empty - append log entry to file
                    using (StreamWriter writeSmsLog = File.AppendText(smsLogfilePath))
                    {
                        writeSmsLog.WriteLine(messageId + "             " + smsFileName + "    " + DateTime.Now + "     " + messageStatus);
                        writeSmsLog.Close();
                    }
                }
                else
                {
                    FileStream fs = File.OpenWrite(smsLogfilePath);
                    fs.Flush();
                    fs.Close();
                    fs.Dispose();

                    using (StreamWriter writeSmsLog = new StreamWriter(smsLogfilePath, true))
                    {
                        writeSmsLog.WriteLine("Message_ID                                       File_Name                                    Date_Sent                  Status");
                        writeSmsLog.WriteLine("======================================================================================================================================");
                        writeSmsLog.WriteLine(messageId + "             " + smsFileName + "    " + DateTime.Now + "     " + messageStatus);
                        writeSmsLog.Close();
                    }
                }

                return "";
            }

            catch (Exception e)
            {
                return Convert.ToString(e);
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T13:28:33+00:00Added an answer on May 30, 2026 at 1:28 pm
    StreamReader smsmessage = new StreamReader(filePath);
    
    try
    {
        FileInfo filenameinfo = new FileInfo(filePath);
        ....
        smsmessage = filenameinfo.OpenText();
        ...
    

    You are initializing smsmessage twice, but only disposing one of those instances. The first line constructs a StreamReader, and then you overwrite your reference to that instance with the instance created by filenameinfo.OpenText(). That leaves you with an instance that no longer has any references and hasn’t been disposed. That instance might be holding a lock on the file and you have no guarantees on when it will be disposed. Even if it isn’t holding a lock, you should still fix this.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a windows service that reads from app.config. I want some settings to
I have a windows service where the app.config file and the log4net.config files are
What I have is a C# windows app that reads a bunch of SQL
I have an windows service that monitors a folder for new files being created.when
We have about 7 app servers running .NET windows services that ping a single
I have a windows app that runs correctly in my PC that is 96DPI
I have an app.Config that was created on the dev machine running Windows 7.
I`m writing client-server app for windows using WinSock and I have class for server.
I have a Windows Service that overrides the OnStart and OnStop methods to call
I created a windows service and installer that watches a collection of files for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.