From 6ec0677555a806c0fd676dfb41e651d2cdaa73de Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=99=88=E5=9B=BD=E4=BC=9F?= <366193849@qq.com>
Date: Tue, 21 Dec 2021 08:59:43 +0800
Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E5=86=B3=20hosts=E6=96=87=E4=BB=B6?=
=?UTF-8?q?=E7=BC=96=E7=A0=81=E9=97=AE=E9=A2=98(#105)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Dns/HostsConflictSolver.cs | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/FastGithub.PacketIntercept/Dns/HostsConflictSolver.cs b/FastGithub.PacketIntercept/Dns/HostsConflictSolver.cs
index b8b5163..59d40ab 100644
--- a/FastGithub.PacketIntercept/Dns/HostsConflictSolver.cs
+++ b/FastGithub.PacketIntercept/Dns/HostsConflictSolver.cs
@@ -46,9 +46,12 @@ namespace FastGithub.PacketIntercept.Dns
var hasConflicting = false;
var hostsBuilder = new StringBuilder();
- var lines = await File.ReadAllLinesAsync(hostsPath, cancellationToken);
- foreach (var line in lines)
+ using var fileStream = new FileStream(hostsPath, FileMode.Open, FileAccess.Read);
+ using var streamReader = new StreamReader(fileStream);
+
+ while (streamReader.EndOfStream == false)
{
+ var line = await streamReader.ReadLineAsync();
if (this.IsConflictingLine(line))
{
hasConflicting = true;
@@ -60,12 +63,13 @@ namespace FastGithub.PacketIntercept.Dns
}
}
+
if (hasConflicting == true)
{
try
{
File.Move(hostsPath, Path.ChangeExtension(hostsPath, ".bak"), overwrite: true);
- await File.WriteAllTextAsync(hostsPath, hostsBuilder.ToString(), cancellationToken);
+ await File.WriteAllTextAsync(hostsPath, hostsBuilder.ToString(), streamReader.CurrentEncoding, cancellationToken);
}
catch (Exception ex)
{
@@ -89,9 +93,9 @@ namespace FastGithub.PacketIntercept.Dns
///
///
///
- private bool IsConflictingLine(string line)
+ private bool IsConflictingLine(string? line)
{
- if (line.TrimStart().StartsWith("#"))
+ if (line == null || line.TrimStart().StartsWith("#"))
{
return false;
}