Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/HostsFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ public int LineCount
}
}

/// <summary>
/// Gets value indicating if the HostsFile is currently disabled.
/// </summary>
public static bool IsDisabled => File.Exists(DefaultDisabledHostFilePath);

#endregion

#region Public Methods
Expand All @@ -191,6 +196,11 @@ public int LineCount
/// </summary>
public static void DisableHostsFile()
{
if (IsEnabled && IsDisabled)
{
throw new InvalidOperationException("The HostsFile is enabled and disabled at the same time.");
}

using (FileEx.DisableAttributes(DefaultHostFilePath, FileAttributes.ReadOnly))
{
File.Move(DefaultHostFilePath, DefaultDisabledHostFilePath);
Expand All @@ -203,6 +213,11 @@ public static void DisableHostsFile()
/// </summary>
public static void EnableHostsFile()
{
if (IsEnabled && IsDisabled)
{
throw new InvalidOperationException("The HostsFile is enabled and disabled at the same time.");
}

using (FileEx.DisableAttributes(DefaultDisabledHostFilePath, FileAttributes.ReadOnly))
{
File.Move(DefaultDisabledHostFilePath, DefaultHostFilePath);
Expand Down
30 changes: 28 additions & 2 deletions src/MainForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -312,11 +312,31 @@ private void OnDisableHostsClick(object sender, EventArgs e)

if (checkState)
{
HostsFile.EnableHostsFile();
try
{
HostsFile.EnableHostsFile();
}
catch (InvalidOperationException invalidOperationException)
{
Console.WriteLine(invalidOperationException);
MessageBox.Show(invalidOperationException.Message, "Error during operation!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
else
{
HostsFile.DisableHostsFile();
try
{
HostsFile.DisableHostsFile();
}
catch (InvalidOperationException invalidOperationException)
{
Console.WriteLine(invalidOperationException);
MessageBox.Show(invalidOperationException.Message, "Error during operation!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}

this.UpdateNotifyIcon();
Expand Down Expand Up @@ -614,6 +634,12 @@ private void OnSaveClick(object sender, EventArgs e)
this.dataGridViewHostsEntries.CommitEdit(
DataGridViewDataErrorContexts.Commit);

if (HostsFile.IsDisabled)
{
MessageBox.Show("The HostsFile is currently disabled. Enable the HostsFile before editing entries.");
return;
}

HostsFile.Instance.Save();
}

Expand Down