一、系统架构设计

二、分层实现
1. Model层(实体类)
// NetworkConfig.cs
namespace Model
{
public class NetworkConfig
{
public string AdapterName {
get; set; } // 网卡名称
public string IPAddress {
get; set; } // IP地址
public string SubnetMask {
get; set; } // 子网掩码
public string Gateway {
get; set; } // 网关
public bool IsDHCP {
get; set; } // 是否启用DHCP
}
}
2. DAL层(数据访问)
// NetworkConfigDAL.cs
using System.Xml.Linq;
using Model;
namespace DAL
{
public class NetworkConfigDAL
{
private const string ConfigPath = "network_config.xml";
// 读取配置
public List<NetworkConfig> GetConfigs()
{
if (!System.IO.File.Exists(ConfigPath))
return new List<NetworkConfig>();
var xml = XDocument.Load(ConfigPath);
return xml.Descendants("Network")
.Select(x => new NetworkConfig
{
AdapterName = x.Element("AdapterName")?.Value,
IPAddress = x.Element("IPAddress")?.Value,
SubnetMask = x.Element("SubnetMask")?.Value,
Gateway = x.Element("Gateway")?.Value,
IsDHCP = (bool?)x.Element("IsDHCP") ?? false
}).ToList();
}
// 保存配置
public void SaveConfig(NetworkConfig config)
{
var xml = new XDocument(
new XElement("NetworkConfigs",
new XElement("Network",
new XElement("AdapterName", config.AdapterName),
new XElement("IPAddress", config.IPAddress),
new XElement("SubnetMask", config.SubnetMask),
new XElement("Gateway", config.Gateway),
new XElement("IsDHCP", config.IsDHCP)
)
)
);
xml.Save(ConfigPath);
}
}
}
3. BLL层(业务逻辑)
// NetworkConfigBLL.cs
using System.Net.NetworkInformation;
using DAL;
using Model;
namespace BLL
{
public class NetworkConfigBLL
{
private readonly NetworkConfigDAL _dal = new NetworkConfigDAL();
// 加载配置
public List<NetworkConfig> LoadConfigs()
{
return _dal.GetConfigs();
}
// 应用配置到网卡
public bool ApplyConfig(NetworkConfig config)
{
var adapter = NetworkInterface.GetAllNetworkInterfaces()
.FirstOrDefault(ni => ni.Name.Equals(config.AdapterName, StringComparison.OrdinalIgnoreCase));
if (adapter == null) return false;
// 禁用DHCP
if (!config.IsDHCP)
{
var managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
var instances = managementClass.GetInstances();
foreach (ManagementObject instance in instances)
{
if (instance["SettingID"].ToString() == adapter.Id)
{
instance.InvokeMethod("EnableDHCP", null); // 关闭DHCP
instance.InvokeMethod("SetGateways", new object[] {
new string[] {
config.Gateway } });
instance.InvokeMethod("EnableStatic", new object[] {
new string[] {
config.IPAddress }, new string[] {
config.SubnetMask } });
return true;
}
}
}
return false;
}
}
}
4. UI层(界面交互)
// MainForm.cs
using System;
using System.Windows.Forms;
using BLL;
using Model;
namespace UI
{
public partial class MainForm : Form
{
private readonly NetworkConfigBLL _bll = new NetworkConfigBLL();
public MainForm()
{
InitializeComponent();
LoadNetworkConfigs();
}
// 加载配置列表
private void LoadNetworkConfigs()
{
var configs = _bll.LoadConfigs();
lstConfigs.Items.Clear();
foreach (var config in configs)
{
lstConfigs.Items.Add($"{config.AdapterName} - {(config.IsDHCP ? "DHCP" : "静态IP")}");
}
}
// 修改IP并保存
private void btnSave_Click(object sender, EventArgs e)
{
var config = new NetworkConfig
{
AdapterName = txtAdapterName.Text,
IPAddress = txtIP.Text,
SubnetMask = txtSubnet.Text,
Gateway = txtGateway.Text,
IsDHCP = chkDHCP.Checked
};
if (_bll.ApplyConfig(config))
{
MessageBox.Show("配置已保存并应用!");
}
else
{
MessageBox.Show("网卡未找到或配置失败!");
}
}
}
}
三、XML配置文件示例
<?xml version="1.0" encoding="utf-8"?>
<NetworkConfigs>
<Network>
<AdapterName>以太网</AdapterName>
<IPAddress>192.168.1.100</IPAddress>
<SubnetMask>255.255.255.0</SubnetMask>
<Gateway>192.168.1.1</Gateway>
<IsDHCP>false</IsDHCP>
</Network>
</NetworkConfigs>
四、关键功能实现
1. 网卡枚举与选择
// 获取所有网卡名称
var adapters = NetworkInterface.GetAllNetworkInterfaces()
.Where(ni => ni.OperationalStatus == OperationalStatus.Up)
.Select(ni => ni.Name)
.ToList();
2. IP地址合法性验证
// 验证IPv4地址格式
public static bool IsValidIP(string ip)
{
return IPAddress.TryParse(ip, out IPAddress addr) && addr.AddressFamily == AddressFamily.InterNetwork;
}
3. 自动获取当前IP(备用方案)
// 自动检测当前IP配置
public NetworkConfig GetCurrentConfig()
{
var adapter = NetworkInterface.GetAllNetworkInterfaces()
.FirstOrDefault(ni => ni.OperationalStatus == OperationalStatus.Up);
if (adapter != null)
{
var ipProps = adapter.GetIPProperties();
return new NetworkConfig
{
AdapterName = adapter.Name,
IPAddress = ipProps.UnicastAddresses
.FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork)?.Address.ToString(),
SubnetMask = ipProps.UnicastAddresses
.FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork)?.GetAddressBytes()
.Take(4).Aggregate("", (s, b) => s + $"{b:X2}.").TrimEnd('.'),
Gateway = ipProps.GatewayAddresses.FirstOrDefault()?.Address.ToString(),
IsDHCP = ipProps.DnsSuffix != null
};
}
return null;
}
五、异常处理与权限
管理员权限声明
在
app.manifest中添加:<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />异常捕获
try { // 网络配置操作 } catch (ManagementException ex) { MessageBox.Show($"WMI操作失败: {ex.Message}"); } catch (UnauthorizedAccessException) { MessageBox.Show("需要管理员权限!"); }
参考代码 IP设置工具(三层构架) www.youwenfan.com/contentalh/37551.html
六、扩展功能
批量配置多网卡
public void BatchApplyConfigs(List<NetworkConfig> configs) { foreach (var config in configs) { ApplyConfig(config); } }配置模板导入导出
// 从文件加载配置 public List<NetworkConfig> ImportConfigs(string filePath) => _dal.GetConfigs(filePath); // 导出配置到文件 public void ExportConfigs(List<NetworkConfig> configs, string filePath) { var xml = new XDocument(new XElement("NetworkConfigs", configs.Select(c => new XElement("Network", new XElement("AdapterName", c.AdapterName), new XElement("IPAddress", c.IPAddress), new XElement("SubnetMask", c.SubnetMask), new XElement("Gateway", c.Gateway), new XElement("IsDHCP", c.IsDHCP))))); xml.Save(filePath); }
七、测试用例
| 场景 | 输入 | 预期结果 |
|---|---|---|
| 修改静态IP | AdapterName=以太网, IP=192.168.1.100 | 网卡IP成功修改,XML记录更新 |
| 启用DHCP | AdapterName=无线网卡, IsDHCP=true | 网卡获取动态IP,XML中DHCP标记为true |
| 加载配置文件 | 读取network_config.xml | 显示历史配置列表 |
八、总结
本方案通过三层架构实现网络配置的解耦管理:
UI层:提供用户交互界面
BLL层:封装业务逻辑(如IP合法性校验、配置应用)
DAL层:负责XML持久化操作
Model层:定义数据实体结构
优势包括:
可维护性:各层职责清晰,便于单独修改
扩展性:支持批量配置、模板导入等扩展功能
健壮性:异常处理机制保障操作安全