Adding entry to Host file

Dec 7, 2010 at 3:50 PM

Hi I'm trying to automate my web application for local development and the only thing I'm unable to do is add a host header to the windows host file (C:\Windows\System32\drivers\etc\hosts).

I've been able to achieve this using my own task library but was hoping something similar is already available in the MSBuild Extension Pack as I'm already using the Web collection tasks and if possible would rather not add another set of .tasks into the project.

I guess what I need to know is, are their a set of tasks for file manipulation?

Coordinator
Dec 7, 2010 at 4:37 PM

Not entirely.

You could use the File task adn FilterByContent to see if your host file contained the entry, then use the MSBuild WriteLinesToFile task.

I need a handy host file updating task too. Can you share your code? I'll see if I can work something into the December release due within 1 to 2 weeks.

Thanks

Mike

 

Dec 7, 2010 at 5:25 PM

What namespace is WriteLinesToFile task in? Can't seem to find it in the extension pack list. Below is the main method I'm using to addHostFileEntry, I also have a removeHostFileEntry aswell which would be the equivalent of FilterByContent but actually removes the hostheader entry you set.

    public sealed class AddHostFileEntry : TaskBase
    {
        #region Private members
        /// <summary>
        /// The id address to add
        /// </summary>
        private string ipAddress;

        #endregion

        #region Public members

        /// <summary>
        /// Gets or sets the host name
        /// </summary>
        [Required]
        public string HostName
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the ip address
        /// </summary>
        public string IPAddress
        {
            get
            {
                if (this.ipAddress == null)
                {
                    this.ipAddress = "127.0.0.1";
                }

                return this.ipAddress;
            }

            set
            {
                this.ipAddress = value;
            }
        }

        #endregion

        #region Private Public members

        /// <summary>
        /// Gets the path to the hosts file
        /// </summary>
        private string Path
        {
            get
            {
                return string.Concat(System.Environment.SystemDirectory, "\\drivers\\etc\\hosts");
            }
        }

        #endregion

        #region Protected Methods

        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            string path = this.Path;

            try
            {
                if (System.IO.File.Exists(path))
                {
                    FileInfo fi = new FileInfo(path);
                    FileAttributes originalAttributes = fi.Attributes;

                    string fileContents = string.Empty;
                    using (StreamReader textFileReader = new StreamReader(path))
                    {
                        string currentLine = string.Empty;
                        bool found = false;

                        while (currentLine != null)
                        {
                            currentLine = textFileReader.ReadLine();

                            if (currentLine != null && currentLine.EndsWith(this.HostName, System.StringComparison.InvariantCultureIgnoreCase))
                            {
                                found = true;
                                currentLine = string.Concat(this.ipAddress, "\t", this.HostName);
                            }

                            if (fileContents.Length > 0)
                            {
                                fileContents += Environment.NewLine;
                            }

                            fileContents += currentLine;
                        }

                        if (found == false)
                        {
                            fileContents += Environment.NewLine;
                            fileContents += string.Concat(this.ipAddress, "\t", this.HostName);
                        }

                        textFileReader.Close();
                    }

                    fi.Attributes = FileAttributes.Normal;

                    using (StreamWriter textFileWriter = new StreamWriter(path))
                    {
                        textFileWriter.Write(fileContents);
                        textFileWriter.Close();
                        textFileWriter.Dispose();
                    }

                    fi.Attributes = originalAttributes;

                    Log.LogMessage(MessageImportance.Normal, "Hosts file updated for ", this.HostName);
                }
                else
                {
                    Log.LogError("File not found: {0}", path);
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.LogError("Failed to add entry: {0}", ex.Message);
            }

            return true;
        }
        #endregion
    }

 

   

 

 

Coordinator
Dec 7, 2010 at 5:32 PM

its here: http://msdn.microsoft.com/en-us/library/ms164305.aspx

 

Thanks, I'll take a look.

 

Mike

Coordinator
Dec 9, 2010 at 3:50 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.
Coordinator
Dec 9, 2010 at 4:38 PM

In the December release you will be able to use the File WriteLines TaskAction.

e.g.

        <FilesToWriteTo Include="C:\a\hosts"/>
        <LinesToRemove Include="192\.156\.236\.25 www\.myurl\.com"/>
        <LinesToRemove Include="192\.156\.234\.25 www\.myurl\.com"/>
        <LinesToRemove Include="192\.156\.23sss4\.25 www\.myurl\.com"/>
        <Lines Include="192.156.236.25 www.myurl.com"/>
        <Lines Include="192.156.234.25 www.myurl.com"/>
    </ItemGroup>
    <Target Name="Default">
        <!-- Write lines to a file. Lines only added if file does not contain them -->
        <MSBuild.ExtensionPack.FileSystem.File TaskAction="WriteLines" Files="@(FilesToWriteTo)" Lines="@(Lines)"/>
        <!-- Remove lines from a file based on regular expressions -->
        <MSBuild.ExtensionPack.FileSystem.File TaskAction="RemoveLines" Files="@(FilesToWriteTo)" Lines="@(LinesToRemove)"/>

If you want to try this out now, see http://msbuildextensionpack.codeplex.com/wikipage?title=DevelopingLatest&referringTitle=Documentation

 

Mike