mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-04-05 10:46:33 +02:00
[Hosts] Handle hidden hosts file (#34308)
* handle hidden hosts file * don't remove hidden attribute
This commit is contained in:
committed by
GitHub
parent
1cbf512ed0
commit
9af757f5ce
@@ -23,6 +23,7 @@ namespace HostsUILib.Helpers
|
||||
public class HostsService : IHostsService, IDisposable
|
||||
{
|
||||
private const string _backupSuffix = $"_PowerToysBackup_";
|
||||
private const int _defaultBufferSize = 4096; // From System.IO.File source code
|
||||
|
||||
private readonly SemaphoreSlim _asyncLock = new SemaphoreSlim(1, 1);
|
||||
private readonly IFileSystem _fileSystem;
|
||||
@@ -197,7 +198,16 @@ namespace HostsUILib.Helpers
|
||||
_backupDone = true;
|
||||
}
|
||||
|
||||
await _fileSystem.File.WriteAllLinesAsync(HostsFilePath, lines, Encoding);
|
||||
// FileMode.OpenOrCreate is necessary to prevent UnauthorizedAccessException when the hosts file is hidden
|
||||
using var stream = _fileSystem.FileStream.Create(HostsFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, _defaultBufferSize, FileOptions.Asynchronous);
|
||||
using var writer = new StreamWriter(stream, Encoding);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
await writer.WriteLineAsync(line.AsMemory());
|
||||
}
|
||||
|
||||
stream.SetLength(stream.Position);
|
||||
await writer.FlushAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -292,7 +302,7 @@ namespace HostsUILib.Helpers
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveReadOnly()
|
||||
public void RemoveReadOnlyAttribute()
|
||||
{
|
||||
var fileInfo = _fileSystem.FileInfo.FromFileName(HostsFilePath);
|
||||
if (fileInfo.IsReadOnly)
|
||||
|
||||
@@ -25,6 +25,6 @@ namespace HostsUILib.Helpers
|
||||
|
||||
void OpenHostsFile();
|
||||
|
||||
void RemoveReadOnly();
|
||||
void RemoveReadOnlyAttribute();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user