NEWS

[C#] Hướng dẫn thêm, xóa, sửa quản lý file Hosts Windows

[C#] Hướng dẫn thêm, xóa, sửa quản lý file Hosts Windows
Đăng bởi: Thảo Meo - Lượt xem: 2248 10:04:11, 18/10/2022DEVEXPRESS   In bài viết

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#:

hosts_file_system

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!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn thêm, xóa, sửa quản lý file Hosts Windows
Đăng bởi: Thảo Meo - Lượt xem: 2248 10:04:11, 18/10/2022DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.