-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathHostsFile.cs
359 lines (309 loc) · 10.4 KB
/
HostsFile.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// <copyright file="HostsFile.cs" company="N/A">
// Copyright 2011 Scott M. Lerch
//
// This file is part of HostsFileEditor.
//
// HostsFileEditor is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 2 of the License, or (at your option)
// any later version.
//
// HostsFileEditor is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with HostsFileEditor. If not, see http://www.gnu.org/licenses/.
// </copyright>
namespace HostsFileEditor
{
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using HostsFileEditor.Extensions;
using HostsFileEditor.Properties;
using HostsFileEditor.Utilities;
using HostsFileEditor.Win32;
/// <summary>
/// This class represents a hosts file.
/// </summary>
internal class HostsFile : INotifyPropertyChanged
{
#region Constants and Fields
/// <summary>
/// The default hosts file directory location.
/// </summary>
public static readonly string DefaultHostFileDirectory =
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Windows),
@"System32\drivers\etc");
/// <summary>
/// The default host file path.
/// </summary>
public static readonly string DefaultHostFilePath =
Path.Combine(DefaultHostFileDirectory, @"hosts");
/// <summary>
/// The default disabled host file path.
/// </summary>
public static readonly string DefaultBackupHostFilePath =
DefaultHostFilePath + ".bak";
/// <summary>
/// The backup host file path.
/// </summary>
public static readonly string DefaultDisabledHostFilePath =
DefaultHostFilePath + ".disabled";
/// <summary>
/// The singleton instance of the hosts file.
/// </summary>
private static readonly Lazy<HostsFile> instance =
new Lazy<HostsFile>(() =>
{
UndoManager.Instance.ClearHistory();
if (IsEnabled)
{
return new HostsFile(DefaultHostFilePath);
}
else
{
return new HostsFile(DefaultDisabledHostFilePath);
}
});
/// <summary>
/// The file path.
/// </summary>
private readonly string filePath;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="HostsFile"/> class.
/// </summary>
/// <param name="filePath">
/// The file path.
/// </param>
private HostsFile(string filePath)
{
this.filePath = filePath;
if (!File.Exists(filePath))
{
this.Entries = new HostsEntryList();
}
else
{
using (FileEx.DisableAttributes(DefaultBackupHostFilePath, FileAttributes.ReadOnly))
{
File.Copy(filePath, DefaultBackupHostFilePath, true);
}
this.Entries = new HostsEntryList(File.ReadAllLines(filePath), RemoveDefaultText);
}
this.Entries.ListChanged += this.OnHostsEntriesListChanged;
}
#endregion
#region Public Events
/// <summary>
/// The property changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = delegate { };
#endregion
#region Public Properties
/// <summary>
/// Gets the singleton instance.
/// </summary>
public static HostsFile Instance
{
get { return instance.Value; }
}
/// <summary>
/// Gets a value indicating whether IsEnabled.
/// </summary>
public static bool IsEnabled
{
get
{
return File.Exists(DefaultHostFilePath);
}
}
/// <summary>
/// Gets or sets a value indicating whether to
/// remove default hosts file text.
/// </summary>
public static bool RemoveDefaultText { get; set; }
/// <summary>
/// Gets EnabledCount.
/// </summary>
public int EnabledCount
{
get
{
return this.Entries.Count(entry => entry.Enabled);
}
}
/// <summary>
/// Gets Entries.
/// </summary>
public HostsEntryList Entries { get; private set; }
/// <summary>
/// Gets LineCount.
/// </summary>
public int LineCount
{
get
{
return this.Entries.Count;
}
}
/// <summary>
/// Gets value indicating if the HostsFile is currently disabled.
/// </summary>
public static bool IsDisabled => File.Exists(DefaultDisabledHostFilePath);
#endregion
#region Public Methods
/// <summary>
/// The disable hosts file.
/// </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);
NativeMethods.FlushDns();
}
}
/// <summary>
/// Enable hosts file.
/// </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);
NativeMethods.FlushDns();
}
}
/// <summary>
/// Import specified hosts file into this hosts file.
/// </summary>
/// <param name="importFilePath">
/// The import file path.
/// </param>
public void Import(string importFilePath)
{
if (this.filePath != importFilePath)
{
this.Entries.BatchUpdate(() =>
{
this.Entries.Clear();
this.Entries.AddLines(File.ReadAllLines(importFilePath), RemoveDefaultText);
});
}
}
/// <summary>
/// Archives the specified name.
/// </summary>
/// <param name="name">The name.</param>
public void Archive(string name)
{
var archive = new HostsArchive(name);
this.SaveAs(archive.FilePath);
HostsArchiveList.Instance.Add(archive);
}
/// <summary>
/// Restore to default OS hosts file.
/// </summary>
public void RestoreDefault()
{
UndoManager.Instance.ClearHistory();
this.Entries.BatchUpdate(() =>
{
this.Entries.Clear();
this.Entries.AddLines(
Resources.hosts.Split(new[] { Environment.NewLine }, StringSplitOptions.None),
false);
});
}
/// <summary>
/// Save the hosts file changes to disk.
/// </summary>
public void Save()
{
this.SaveAs(this.filePath);
NativeMethods.FlushDns();
}
/// <summary>
/// Save the hosts file to the specified file.
/// </summary>
/// <param name="saveFilePath">
/// The save file path.
/// </param>
public void SaveAs(string saveFilePath)
{
FileInfo info = new FileInfo(saveFilePath);
if (!Directory.Exists(info.DirectoryName))
{
Directory.CreateDirectory(info.DirectoryName);
}
using (FileEx.DisableAttributes(saveFilePath, FileAttributes.ReadOnly))
{
File.WriteAllLines(
saveFilePath,
this.Entries.Select(entry => entry.UnparsedText));
}
}
/// <summary>
/// Refreshes to reflect current hosts file.
/// </summary>
/// <param name="removeDefault">
/// if set to <c>true</c> remove default entries.
/// </param>
public void Refresh(bool removeDefault = true)
{
UndoManager.Instance.ClearHistory();
this.Entries.BatchUpdate(() =>
{
this.Entries.Clear();
this.Entries.AddLines(File.ReadAllLines(this.filePath), removeDefault);
});
NativeMethods.FlushDns();
}
#endregion
#region Methods
/// <summary>
/// Raise property changed event.
/// </summary>
/// <param name="property">
/// The property.
/// </param>
/// <typeparam name="T">
/// Type of object containing property.
/// </typeparam>
protected void OnPropertyChanged<T>(Expression<Func<T>> property)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(property.GetPropertyName()));
}
/// <summary>
/// Occurs when the hosts entries list changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The event arguments.
/// </param>
private void OnHostsEntriesListChanged(object sender, ListChangedEventArgs e)
{
this.OnPropertyChanged(() => this.LineCount);
this.OnPropertyChanged(() => this.EnabledCount);
}
#endregion
}
}