解决 hosts文件编码问题(#105)
This commit is contained in:
parent
baf0d2f304
commit
6ec0677555
@ -46,9 +46,12 @@ namespace FastGithub.PacketIntercept.Dns
|
|||||||
|
|
||||||
var hasConflicting = false;
|
var hasConflicting = false;
|
||||||
var hostsBuilder = new StringBuilder();
|
var hostsBuilder = new StringBuilder();
|
||||||
var lines = await File.ReadAllLinesAsync(hostsPath, cancellationToken);
|
using var fileStream = new FileStream(hostsPath, FileMode.Open, FileAccess.Read);
|
||||||
foreach (var line in lines)
|
using var streamReader = new StreamReader(fileStream);
|
||||||
|
|
||||||
|
while (streamReader.EndOfStream == false)
|
||||||
{
|
{
|
||||||
|
var line = await streamReader.ReadLineAsync();
|
||||||
if (this.IsConflictingLine(line))
|
if (this.IsConflictingLine(line))
|
||||||
{
|
{
|
||||||
hasConflicting = true;
|
hasConflicting = true;
|
||||||
@ -60,12 +63,13 @@ namespace FastGithub.PacketIntercept.Dns
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (hasConflicting == true)
|
if (hasConflicting == true)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
File.Move(hostsPath, Path.ChangeExtension(hostsPath, ".bak"), overwrite: true);
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@ -89,9 +93,9 @@ namespace FastGithub.PacketIntercept.Dns
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="line"></param>
|
/// <param name="line"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private bool IsConflictingLine(string line)
|
private bool IsConflictingLine(string? line)
|
||||||
{
|
{
|
||||||
if (line.TrimStart().StartsWith("#"))
|
if (line == null || line.TrimStart().StartsWith("#"))
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user