https://github.com/encodeous/hosts.net
Cross-platform hosts file modification library for .NET.
https://github.com/encodeous/hosts.net
Last synced: 6 months ago
JSON representation
Cross-platform hosts file modification library for .NET.
- Host: GitHub
- URL: https://github.com/encodeous/hosts.net
- Owner: encodeous
- License: mit
- Created: 2022-07-15T21:34:08.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-01-03T17:50:53.000Z (about 2 years ago)
- Last Synced: 2024-08-11T00:47:53.537Z (over 1 year ago)
- Language: C#
- Homepage: https://www.nuget.org/packages/hosts.net
- Size: 18.6 KB
- Stars: 7
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# `hosts.net`

`hosts.net` is a simple library that enables developers to easily develop applications that can programmatically manipulate the hosts file across various platforms.
## `installation`
```shell
dotnet add package hosts.net
```
## `usage`
**Editing the hosts file on unix requires sudo permission, and likewise administrator is required on Windows.**
*On Unix-like Systems:* `hosts.net` will default to the `/etc/hosts` file.
*On Windows Systems:* the library will default to the `C:/Windows/System32/drivers/etc/hosts` file. The library automatically handles Windows' Access Control List. If any issues arise from this please file an issue.
**Demo Code:**
```csharp
using System.Linq;
using System.Net;
using hosts.net;
// open the file
var file = Hosts.OpenHostsFile(/* optional file path */);
// use linq to query the entries to prevent duplicate entries
if (file.Entries.Any(entry => entry.Comment is not null && entry.Comment == "Added with hosts.net")) return;
file.AddBlankEntry()
.SetComment("Added with hosts.net");
file.AddBlankEntry()
.SetHost(/* address */ IPAddress.Loopback, /* canonical hostname */ "non-existent.domain.n", /* optional aliases */ "non-existent.alias.n");
// other code here...
// save to the disk
file.Write();
// Result:
// # Added with hosts.net
// 127.0.0.1 non-existent.domain.n non-existent.alias.n
```
**Removing an entry with LINQ:**
```csharp
file.Entries.RemoveAll(entry => entry.CanonicalHostname == "encodeous.ca");
```
**Adding an empty line:**
```csharp
file.AddBlankEntry();
```
**Reading & Printing all of the lines:**
```csharp
Console.WriteLine(string.Join('\n',
file.Entries.Select(x => x.RawString))
);
```