Click here to Skip to main content
15,892,199 members
Articles / Desktop Programming / Win32

IP Watchdog: Simple Windows Service Written in C#

Rate me:
Please Sign up or sign in to vote.
4.71/5 (50 votes)
14 Aug 2012CPOL9 min read 115.7K   5.3K   170  
Self-installing windows service that monitors computer's WAN address and sends e-mail when it changes
using System;
using System.IO;
using IpWatchDog.Log;

namespace IpWatchDog
{
    class IpPersistor : IIpPersistor
    {
        private string _path;
        private ILog _log;

        public IpPersistor(ILog log)
        {
            _log = log;
            var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var folder = Path.Combine(appData, "IpWatchDog");
            Directory.CreateDirectory(folder);
            _path = Path.Combine(folder, "currentIp.txt");
        }

        public string GetIp()
        {
            if (!File.Exists(_path)) return null;
            try
            {
                using (var reader = new StreamReader(_path))
                {
                    return reader.ReadToEnd().Trim();
                }
            }
            catch (Exception ex)
            {
                _log.Write(LogLevel.Warning, "Error reading IP from storage. {0}", ex);
                return null;
            }
        }

        public void SaveIp(string ip)
        {
            try
            {
                using (var writer = new StreamWriter(_path))
                {
                    writer.Write(ip);
                }
            }
            catch (Exception ex)
            {
                _log.Write(LogLevel.Warning, "Error writing IP to storage. {0}", ex);
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Thomson Reuters
United States United States
Ivan is a hands-on software architect/technical lead working for Thomson Reuters in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.

Please visit my web site: www.ikriv.com.

Comments and Discussions