- [C#] Di chuyển và thay đổi kích thước Control Winform khi ứng dụng đang chạy
- [VB.NET] Chia sẻ source tạo sắp xếp đội hình bóng đá Line-ups đội bóng
- [C#] Hướng dẫn chỉnh sửa Text của label trực tiếp trên winform
- [C#] Hướng dẫn custom TextBox giống Ultraviewer trên Winform
- [C#] Show Modal Winform like Bootstrap
- [DATABASE] Thứ tự thực hiện mệnh đề truy vấn SELECT trong Sqlserver
- [C#] Hướng dẫn viết addin Excel Lấy hình ảnh từ URL internet vào Excel
- [DATABASE] TSQL view max length all column data trên table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng MailMerge kèm Hình ảnh trên Winform
- [DATABASE] Hướng dẫn truy vấn xem kích thước lưu trữ của từng bảng ghi Table trên sqlserver
- [C#] Hướng dẫn Fake Date Time sử dụng thư viện Harmony
- [DATABASE] Phân biệt câu lệnh DDL và DML trong sqlserver
- [C#] Hướng dẫn convert file mã HTML sang file Pdf trên winform
- [DEVEXPRESS] Tạo các loại mã vạch Barcode trực tiếp trên Devexpress Barcode API
- [DEVEXPRESS] Hướng dẫn custom Simple button thành Progressbar
- [DATABASE] Tách số và chữ từ chuỗi - hàm tối ưu hóa tách số và chữ trong Sqlserver
- [C#] Tìm kiếm gần đúng Full Text Search sử dụng thư viện Lucene.NET
- [C#] Chia sẻ tài liệu, sdk và source code máy chấm công dòng máy ZKTeco
- [C#] Memory Cache là gì, và sử dụng trong ứng dụng Winform
- [DATABASE] Khóa chính Primary Key trong Sqlserver
[C#] Hướng dẫn thêm, xóa, sửa quản lý file Hosts Windows
Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục hướng dẫn các bạn cách thêm, xóa, sửa quản lý file Hosts trong Windows bằng ngôn ngữ lập trình C#, Winform.
[C#] Hosts Windows File Manager
Vậy file Hosts Windows là gì?
File host là một tệp tin (file) lưu trữ thông tin địa chỉ IP của máy chủ và domain được trỏ tới. File host được xem như là một DNS nhỏ trên máy tính của bạn.
Tệp tin này giúp các hệ điều hành có thể biết được IP của máy chủ nơi tên miền được quản lý.
Cách mở file host trên hệ điều hành Windows, macOS và Linux bằng cách mở các folder bằng đường dẫn sau:
- Trên Windows: C:\Windows\System32\drivers\etc
Giao diện demo ứng dụng Quản lý File Hosts Windows C#:
Với ứng dụng này, các bạn dễ dàng thêm xóa sửa vào file hosts một cách dễ dàng.
Video demo ứng dụng:
Các bước thực hiện:
Bước 1: Tạo 1 class Model HostsEntry.cs
namespace HostsFileWindowsManager
{
public class HostsEntry
{
public string Address;
public string Host;
public bool Enabled;
}
}
Bước 2: Tạo tiếp 1 class HostsFileManager.cs
dùng để làm việc với file hosts
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Text;
namespace HostsFileWindowsManager
{
public static class HostsFileManager
{
public const string DISABLED_INDICATOR = "# disabled ";
public static List<HostsEntry> Entries = new List<HostsEntry>();
public static string Filename
{
get
{
return Path.Combine(Environment.SystemDirectory, @"drivers\etc\hosts");
}
}
public static HostsEntry FindEntry(String hostname)
{
foreach (HostsEntry entry in Entries)
{
if (entry.Host == hostname)
{
return entry;
}
}
return null;
}
public static void DeleteEntry(String hostname)
{
foreach (HostsEntry entry in Entries)
{
if (entry.Host == hostname)
{
Entries.Remove(entry);
break;
}
}
}
public static string GenerateHostsText()
{
string[] lines = GenerateHostsLines();
StringBuilder outText = new StringBuilder();
foreach (string ln in lines)
{
outText.Append(ln);
outText.Append(Environment.NewLine);
}
return outText.ToString();
}
public static string[] GenerateHostsLines()
{
List<string> outLines = new List<string>();
List<string> seenHosts = new List<string>();
var raw = File.ReadAllLines(Filename);
foreach (string line in raw)
{
bool isDisabledEntry = line.StartsWith(DISABLED_INDICATOR);
if (line.StartsWith("#") && !isDisabledEntry)
{
outLines.Add(line);
continue;
}
string aLine = line;
if (isDisabledEntry)
{
aLine = line.Substring(DISABLED_INDICATOR.Length).Trim();
}
string[] parts = aLine
.Replace('\t', ' ')
.Trim()
.Split(' ');
if (parts.Length == 2)
{
String address = parts[0];
String host = parts[1];
if (seenHosts.Contains(host))
{
continue;
}
seenHosts.Add(host);
HostsEntry customEntry = FindEntry(host);
// If we do not have a mutation for this line it has been deleted in the editor (or added after saving)
if (customEntry == null)
{
continue;
}
// If we DO have an entry, it might have been mutated by the editor, so provide an alternate version of this line
else
{
StringBuilder customLine = new StringBuilder();
if (!customEntry.Enabled)
{
customLine.Append(DISABLED_INDICATOR);
}
customLine.Append(customEntry.Address);
customLine.Append(" ");
customLine.Append(customEntry.Host);
outLines.Add(customLine.ToString());
}
}
else
{
outLines.Add(line);
}
}
foreach (HostsEntry customEntry in Entries)
{
if (seenHosts.Contains(customEntry.Host))
{
continue;
}
StringBuilder customLine = new StringBuilder();
if (!customEntry.Enabled)
{
customLine.Append(DISABLED_INDICATOR);
}
customLine.Append(customEntry.Address);
customLine.Append(" ");
customLine.Append(customEntry.Host);
outLines.Add(customLine.ToString());
}
return outLines.ToArray();
}
public static void RefreshData()
{
Entries.Clear();
var raw = File.ReadAllLines(Filename);
foreach (string line in raw)
{
bool isDisabledEntry = line.StartsWith(DISABLED_INDICATOR);
if (line.StartsWith("#") && !isDisabledEntry)
{
continue;
}
string aLine = line;
if (isDisabledEntry)
{
aLine = line.Substring(DISABLED_INDICATOR.Length).Trim();
}
string[] parts = aLine
.Replace('\t', ' ')
.Trim()
.Split(' ');
if (parts.Length != 2)
{
continue;
}
Entries.Add(new HostsEntry()
{
Address = parts[0],
Host = parts[1],
Enabled = !isDisabledEntry
});
}
}
public static void Save()
{
File.WriteAllLines(HostsFileManager.Filename, GenerateHostsLines());
}
public static void LoadDataToListView(String[] raw, ListView lsv)
{
lsv.Items.Clear();
foreach (string line in raw)
{
bool isDisabledEntry = line.StartsWith(HostsFileManager.DISABLED_INDICATOR);
if (line.StartsWith("#") && !isDisabledEntry)
{
}
else
{
string aLine = line;
if (isDisabledEntry)
{
aLine = line.Substring(HostsFileManager.DISABLED_INDICATOR.Length).Trim();
}
string[] parts = aLine
.Replace('\t', ' ')
.Trim()
.Split(' ');
if (parts.Length == 2)
{
String Address = parts[0];
String Host = parts[1];
var lvi = new ListViewItem()
{
Text = isDisabledEntry ? "No" : "Yes"
};
lvi.SubItems.Add(Host);
lvi.SubItems.Add(Address);
lvi.Tag = Host;
lsv.Items.Add(lvi);
}
}
}
}
}
}
Bước 3: Source code trên Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HostsFileWindowsManager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RefreshData();
}
public void RefreshData()
{
HostsFileManager.RefreshData();
HostsFileManager.LoadDataToListView(HostsFileManager.GenerateHostsLines(), listView1);
}
private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
{
EditDialog dialog = new EditDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
HostsFileManager.Save();
RefreshData();
}
}
private ListViewItem GetSelectedEntry()
{
if (listView1.SelectedItems.Count != 1)
{
return null;
}
return listView1.SelectedItems[0];
}
private void toggleEnabledToolStripMenuItem_Click(object sender, EventArgs e)
{
ListViewItem selectedItem = GetSelectedEntry();
if (selectedItem == null)
{
return;
}
String hostname = (String)selectedItem.Tag;
HostsEntry entry = HostsFileManager.FindEntry(hostname);
if (entry == null)
{
return;
}
entry.Enabled = !entry.Enabled;
HostsFileManager.Save();
RefreshData();
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
ListViewItem selectedItem = GetSelectedEntry();
if (selectedItem == null)
{
return;
}
String hostname = (String)selectedItem.Tag;
HostsFileManager.DeleteEntry(hostname);
HostsFileManager.Save();
RefreshData();
}
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
ListViewItem selectedItem = GetSelectedEntry();
if (selectedItem == null)
{
return;
}
String hostname = (String)selectedItem.Tag;
HostsEntry entry = HostsFileManager.FindEntry(hostname);
if (entry == null)
{
return;
}
EditDialog dialog = new EditDialog(entry);
if (dialog.ShowDialog() == DialogResult.OK)
{
HostsFileManager.Save();
RefreshData();
}
}
}
}
Thanks for watching!