diff --git a/src/HostsFile.cs b/src/HostsFile.cs index ea1b131..2d5c1af 100644 --- a/src/HostsFile.cs +++ b/src/HostsFile.cs @@ -182,6 +182,11 @@ public int LineCount } } + /// + /// Gets value indicating if the HostsFile is currently disabled. + /// + public static bool IsDisabled => File.Exists(DefaultDisabledHostFilePath); + #endregion #region Public Methods @@ -191,6 +196,11 @@ public int LineCount /// 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); @@ -203,6 +213,11 @@ public static void DisableHostsFile() /// 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); diff --git a/src/MainForm.cs b/src/MainForm.cs index 94177d7..af66bbd 100644 --- a/src/MainForm.cs +++ b/src/MainForm.cs @@ -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(); @@ -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(); }