1. C# 中的文件压缩和解压缩(ZipFile 类)
using System;
using System.IO;
using System.IO.Compression;
class Program
{
static void Main()
{
string zipPath = @"C:\example.zip";
string extractPath = @"C:\extract";
// 压缩文件
ZipFile.CreateFromDirectory(extractPath, zipPath);
Console.WriteLine("文件已压缩.");
// 解压缩文件
ZipFile.ExtractToDirectory(zipPath, extractPath);
Console.WriteLine("文件已解压缩.");
}
}
用途: 演示如何使用C#中的 ZipFile
类进行文件的压缩和解压缩操作,常用于文件传输和存储优化。
2. 使用 Stopwatch 进行性能测试
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Thread.Sleep(1000); // 模拟延时
stopwatch.Stop();
Console.WriteLine($"运行时间: {
stopwatch.ElapsedMilliseconds} 毫秒");
}
}
用途: 测量代码段的执行时间,方便进行性能调优。
3. 使用 MailMessage 和 SmtpClient 发送电子邮件
using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main()
{
MailMessage message = new MailMessage("[email protected]", "[email protected]");
message.Subject = "测试邮件";
message.Body = "这是一封通过C#发送的测试邮件";
SmtpClient client = new SmtpClient("smtp.example.com");
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("[email protected]", "your-password");
client.Send(message);
Console.WriteLine("邮件已发送");
}
}
用途: 实现如何通过 SmtpClient
发送电子邮件,适合于通知和报警系统。
4. 使用 System.Drawing
生成二维码
using System;
using System.Drawing;
using QRCoder;
class Program
{
static void Main()
{
string qrText = "https://www.example.com";
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);
qrCodeImage.Save("qrcode.png");
Console.WriteLine("二维码已生成");
}
}
用途: 使用 QRCoder
生成二维码,常用于快速分享链接或信息。
5. 通过 SerialPort
类进行串口通信
using System;
using System.IO.Ports;
class Program
{
static void Main()
{
SerialPort port = new SerialPort("COM3", 9600);
port.Open();
port.WriteLine("Hello, Serial!");
string response = port.ReadLine();
Console.WriteLine($"接收到串口数据: {
response}");
port.Close();
}
}
用途: 实现与串口设备进行通信,适用于工控设备或嵌入式设备的串行接口。
6. 多线程中的互斥锁(Mutex)
using System;
using System.Threading;
class Program
{
static Mutex mutex = new Mutex();
static void Main()
{
for (int i = 0; i < 5; i++)
{
new Thread(ThreadTask).Start();
}
}
static void ThreadTask()
{
mutex.WaitOne();
Console.WriteLine($"线程 {
Thread.CurrentThread.ManagedThreadId} 正在运行...");
Thread.Sleep(1000);
mutex.ReleaseMutex();
}
}
用途: 使用 Mutex
控制多线程对资源的访问,确保线程安全。
7. 异步文件读写
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string filePath = "example.txt";
string content = "Hello, World!";
await File.WriteAllTextAsync(filePath, content);
Console.WriteLine("文件已写入");
string readContent = await File.ReadAllTextAsync(filePath);
Console.WriteLine($"读取内容: {
readContent}");
}
}
用途: 使用异步方式进行文件读写操作,适合于大文件的处理。
8. 通过 Process
启动外部程序
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.Start();
Console.WriteLine("记事本已启动");
}
}
用途: 使用C#启动外部程序,如记事本或命令行工具。
9. 使用 MemoryStream 进行内存数据处理
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
byte[] byteArray = Encoding.UTF8.GetBytes("Hello, MemoryStream!");
using (MemoryStream stream = new MemoryStream(byteArray))
{
stream.Write(byteArray, 0, byteArray.Length);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
Console.WriteLine(result);
}
}
}
用途: 使用 MemoryStream
进行高效的内存中数据处理,适合于无需磁盘IO的场景。
10. 使用 LINQ to XML 处理 XML 数据
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
string xml = "<Persons><Person Name='John' Age='30' /></Persons>";
XElement root = XElement.Parse(xml);
var person = root.Elements("Person").FirstOrDefault();
Console.WriteLine($"姓名: {
person?.Attribute("Name")?.Value}, 年龄: {
person?.Attribute("Age")?.Value}");
}
}
用途: 使用 LINQ 查询和处理 XML 数据,适合配置文件或结构化数据。
11. 通过反射创建实例和调用方法
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type type = typeof(SampleClass);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("SampleMethod");
method.Invoke(instance, new object[] {
"Hello, Reflection!" });
}
}
class SampleClass
{
public void SampleMethod(string message)
{
Console.WriteLine(message);
}
}
用途: 使用反射动态创建对象和调用方法,适合于插件或动态加载类库的场景。
12. 使用 Parallel.For 并行处理集合
using System;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Parallel.For(0, 10, i =>
{
Console.WriteLine($"任务 {
i} 正在运行...");
});
}
}
用途: 使用 Parallel.For
进行并行循环,提升性能,适合于 CPU 密集型任务。
13. 使用 ConfigurationManager
读取应用程序配置文件
using System;
using System.Configuration;
class Program
{
static void Main()
{
string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
Console.WriteLine($"连接字符串: {
connectionString}");
}
}
用途: 读取 app.config
或 web.config
中的配置,适合于应用程序的配置管理。
14. 通过 Entity Framework
进行数据库操作
using System;
using System.Linq;
using System.Data.Entity;
class Program
{
static void Main()
{
using (var context = new MyDbContext())
{
var users = context.Users.ToList();
foreach (var user in users)
{
Console.WriteLine(user.Name);
}
}
}
}
public class MyDbContext : DbContext
{
public
DbSet<User> Users {
get; set; }
}
public class User
{
public int Id {
get; set; }
public string Name {
get; set; }
}
用途: 使用 Entity Framework
进行数据库操作,简化数据访问代码。
15. 使用 HttpClient
进行 GET 请求
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
用途: 使用 HttpClient
进行网络请求,常用于API通信。
这些实战示例涵盖了从基础操作到高级应用的多种场景,可以直接用于实际项目或作为练手的demo。希望这些符合你的胃口!~