关闭读取的文件

This commit is contained in:
陈国伟 2021-12-21 09:24:10 +08:00
parent 6ec0677555
commit 5daa5b987a

View File

@ -44,11 +44,12 @@ namespace FastGithub.PacketIntercept.Dns
return;
}
Encoding hostsEncoding;
var hasConflicting = false;
var hostsBuilder = new StringBuilder();
using var fileStream = new FileStream(hostsPath, FileMode.Open, FileAccess.Read);
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();
@ -62,14 +63,15 @@ namespace FastGithub.PacketIntercept.Dns
hostsBuilder.AppendLine(line);
}
}
hostsEncoding = streamReader.CurrentEncoding;
}
if (hasConflicting == true)
{
try
{
File.Move(hostsPath, Path.ChangeExtension(hostsPath, ".bak"), overwrite: true);
await File.WriteAllTextAsync(hostsPath, hostsBuilder.ToString(), streamReader.CurrentEncoding, cancellationToken);
await File.WriteAllTextAsync(hostsPath, hostsBuilder.ToString(), hostsEncoding, cancellationToken);
}
catch (Exception ex)
{