C# WPF 创建一个动态程序集 在读取文件获取MAC值
要创建一个动态程序集并读取文件获取MAC值,你可以按照以下步骤进行操作:
-
创建一个新的C# WPF项目。
-
在项目中添加一个类文件,用于处理读取文件和获取MAC值的逻辑。例如,可以创建一个名为
MacHelper.cs的类文件。 -
在
MacHelper.cs文件中,添加以下代码:
using System.IO;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
public static class MacHelper
{
public static string GetMacValue(string filePath)
{
// 读取文件内容
string fileContent = File.ReadAllText(filePath);
// 计算文件内容的MD5哈希值
byte[] fileBytes = Encoding.UTF8.GetBytes(fileContent);
MD5 md5 = MD5.Create();
byte[] hashBytes = md5.ComputeHash(fileBytes);
string md5Hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
// 获取本地MAC地址
string macAddress = GetMacAddress();
// 将文件内容的MD5哈希值和MAC地址拼接在一起作为最终的MAC值
string macValue = $"{md5Hash}-{macAddress}";
return macValue;
}
private static string GetMacAddress()
{
string macAddress = "";
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in interfaces)
{
if (nic.OperationalStatus == OperationalStatus.Up && !nic.Description.ToLower().Contains("virtual") && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
macAddress = nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddress;
}
}
- 在WPF的
MainWindow.xaml.cs文件中,添加以下代码,用于调用MacHelper类并获取MAC值:
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string filePath = "path/to/your/file.txt"; // 替换为你的文件路径
string macValue = MacHelper.GetMacValue(filePath);
MessageBox.Show($"MAC Value: {macValue}");
}
}
- 在
MainWindow.xaml文件中,添加一个按钮控件并设置点击事件:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Get MAC Value" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
- 运行项目,点击按钮将会弹出一个消息框显示MAC值。
请确保替换代码中的文件路径为你实际的文件路径,并确保文件存在
原文地址: https://www.cveoy.top/t/topic/hNRh 著作权归作者所有。请勿转载和采集!