C# 学习笔记:从IO文件操作到窗体应用开发

张开发
2026/4/13 4:14:30 15 分钟阅读

分享文章

C# 学习笔记:从IO文件操作到窗体应用开发
前言在C#学习过程中从IO文件操作到窗体应用开发是一个重要的进阶阶段。本文将系统总结day14到day17的学习内容涵盖文件读写、多线程编程、窗体复习以及高级窗体应用等内容帮助读者建立起完整的知识体系。一、IO文件操作day141.1 文件系统基础C#中的IO操作主要位于System.IO命名空间下提供了丰富的类用于文件和目录的操作。核心类介绍csharpusing System.IO; // File类提供静态方法操作文件 File.Exists(path); // 判断文件是否存在 File.Copy(source, dest); // 复制文件 File.Move(source, dest); // 移动文件 File.Delete(path); // 删除文件 // Directory类提供静态方法操作目录 Directory.CreateDirectory(path); // 创建目录 Directory.Delete(path); // 删除目录 Directory.GetFiles(path); // 获取目录下所有文件 // FileInfo类实例方法操作文件 FileInfo fileInfo new FileInfo(path); fileInfo.Length; // 文件大小 fileInfo.Extension; // 文件扩展名 fileInfo.CreationTime; // 创建时间 // DirectoryInfo类实例方法操作目录 DirectoryInfo dirInfo new DirectoryInfo(path); dirInfo.GetFiles(); // 获取文件列表 dirInfo.GetDirectories(); // 获取子目录列表1.2 文件读写操作文本文件读写csharp// 写入文本文件 string content Hello, World!; File.WriteAllText(test.txt, content); // 读取文本文件 string readContent File.ReadAllText(test.txt); // 追加内容 File.AppendAllText(test.txt, 追加的内容); // 按行读写 string[] lines { 第一行, 第二行, 第三行 }; File.WriteAllLines(lines.txt, lines); string[] readLines File.ReadAllLines(lines.txt); // 使用StreamReader/StreamWriter using (StreamWriter writer new StreamWriter(output.txt)) { writer.WriteLine(使用StreamWriter写入); writer.Write(不换行写入); } using (StreamReader reader new StreamReader(output.txt)) { string line reader.ReadLine(); string all reader.ReadToEnd(); }二进制文件读写csharp// 写入二进制文件 byte[] data { 0x00, 0x01, 0x02, 0x03 }; File.WriteAllBytes(data.bin, data); // 读取二进制文件 byte[] readData File.ReadAllBytes(data.bin); // 使用BinaryWriter/BinaryReader using (BinaryWriter writer new BinaryWriter(File.Open(data.dat, FileMode.Create))) { writer.Write(100); // 写入整数 writer.Write(3.14); // 写入浮点数 writer.Write(字符串); // 写入字符串 } using (BinaryReader reader new BinaryReader(File.Open(data.dat, FileMode.Open))) { int num reader.ReadInt32(); double pi reader.ReadDouble(); string str reader.ReadString(); }1.3 文件和目录操作示例csharppublic class FileManager { // 复制目录 public static void CopyDirectory(string sourceDir, string destDir) { DirectoryInfo source new DirectoryInfo(sourceDir); DirectoryInfo dest new DirectoryInfo(destDir); if (!dest.Exists) dest.Create(); // 复制文件 foreach (FileInfo file in source.GetFiles()) { file.CopyTo(Path.Combine(dest.FullName, file.Name), true); } // 递归复制子目录 foreach (DirectoryInfo subDir in source.GetDirectories()) { CopyDirectory(subDir.FullName, Path.Combine(dest.FullName, subDir.Name)); } } // 获取文件大小 public static long GetDirectorySize(string path) { DirectoryInfo dir new DirectoryInfo(path); long size 0; foreach (FileInfo file in dir.GetFiles(*, SearchOption.AllDirectories)) { size file.Length; } return size; } }二、多线程编程day152.1 线程基础多线程允许程序同时执行多个任务提高程序响应速度和资源利用率。csharpusing System.Threading; // 创建线程 Thread thread new Thread(new ThreadStart(DoWork)); thread.Start(); // 带参数的线程 Thread threadWithParam new Thread(new ParameterizedThreadStart(DoWorkWithParam)); threadWithParam.Start(参数); // Lambda表达式创建线程 Thread lambdaThread new Thread(() { Console.WriteLine(线程执行中...); }); lambdaThread.Start(); // 前台线程与后台线程 thread.IsBackground true; // 设置为后台线程 // 线程等待 thread.Join(); // 等待线程完成 // 线程休眠 Thread.Sleep(1000); // 休眠1秒2.2 线程安全与锁csharppublic class BankAccount { private decimal balance; private readonly object lockObj new object(); public void Deposit(decimal amount) { lock (lockObj) { balance amount; } } public void Withdraw(decimal amount) { lock (lockObj) { if (balance amount) balance - amount; } } // 使用Monitor public void SafeOperation() { Monitor.Enter(lockObj); try { // 临界区代码 } finally { Monitor.Exit(lockObj); } } // 使用Interlocked原子操作 private int counter; public void Increment() { Interlocked.Increment(ref counter); } }2.3 Task异步编程csharpusing System.Threading.Tasks; // 创建并启动Task Task task Task.Run(() { Console.WriteLine(Task执行中); }); // 带返回值的Task Taskint taskWithResult Task.Run(() { return 100; }); int result taskWithResult.Result; // Task等待 Task.WaitAll(task1, task2); // 等待所有Task完成 Task.WaitAny(task1, task2); // 等待任意一个Task完成 // 延续任务 Task task1 Task.Run(() 10); Task task2 task1.ContinueWith(t { Console.WriteLine($上一个任务的结果{t.Result}); });2.4 线程池csharp// 使用线程池执行任务 ThreadPool.QueueUserWorkItem(state { Console.WriteLine(线程池执行的任务); }); // 设置线程池大小 ThreadPool.SetMinThreads(2, 2); ThreadPool.SetMaxThreads(10, 10);三、窗体复习day163.1 窗体基本操作csharp// 窗体常用属性和方法 public partial class MainForm : Form { public MainForm() { // 窗体设置 this.Text 窗体标题; this.Size new Size(800, 600); this.StartPosition FormStartPosition.CenterScreen; this.FormBorderStyle FormBorderStyle.FixedSingle; this.MaximizeBox false; this.MinimizeBox true; this.BackColor Color.White; this.Icon new Icon(app.ico); } // 窗体事件 private void MainForm_Load(object sender, EventArgs e) { // 窗体加载时执行 } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // 窗体关闭前执行 DialogResult result MessageBox.Show(确定退出吗, 提示, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result DialogResult.No) e.Cancel true; } }3.2 控件使用csharp// 动态创建控件 Button myButton new Button(); myButton.Text 点击我; myButton.Location new Point(100, 100); myButton.Size new Size(100, 40); myButton.Click (s, e) { MessageBox.Show(按钮被点击了); }; this.Controls.Add(myButton); // 常用控件 // Label - 显示文本 Label label new Label() { Text 标签文本, TextAlign ContentAlignment.MiddleCenter }; // TextBox - 输入框 TextBox textBox new TextBox() { Text 默认文本, PasswordChar *, ReadOnly false }; // ComboBox - 下拉框 ComboBox comboBox new ComboBox(); comboBox.Items.AddRange(new[] { 选项1, 选项2, 选项3 }); comboBox.SelectedIndex 0; // ListBox - 列表框 ListBox listBox new ListBox(); listBox.Items.AddRange(new[] { 项目1, 项目2, 项目3 });3.3 窗体间导航csharp// 登录窗体 public partial class LoginForm : Form { private void btnLogin_Click(object sender, EventArgs e) { if (username admin password 123456) { this.Hide(); // 隐藏当前窗体 MainForm mainForm new MainForm(); mainForm.Show(); } } } // 主窗体 public partial class MainForm : Form { private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); // 退出整个应用程序 } protected override void OnFormClosed(FormClosedEventArgs e) { base.OnFormClosed(e); Application.Exit(); // 确保应用程序退出 } }四、高级窗体应用day174.1 猜数字游戏实现csharppublic partial class GuessNumberForm : Form { private Timer rollTimer; private Timer clockTimer; private int currentNumber 9; public GuessNumberForm() { InitializeComponent(); // 滚动定时器 rollTimer new Timer(); rollTimer.Interval 100; rollTimer.Tick (s, e) { currentNumber (currentNumber - 1 10) % 10; lblNumber.Text currentNumber.ToString(); }; // 时钟定时器 clockTimer new Timer(); clockTimer.Interval 1000; clockTimer.Tick (s, e) { lblTime.Text DateTime.Now.ToString(HH:mm:ss); }; clockTimer.Start(); } private void btnStart_Click(object sender, EventArgs e) { if (!int.TryParse(txtGuess.Text, out int guess) || guess 0 || guess 9) { MessageBox.Show(请输入0-9之间的数字); return; } rollTimer.Start(); } private void btnStop_Click(object sender, EventArgs e) { rollTimer.Stop(); int guess int.Parse(txtGuess.Text); if (guess currentNumber) MessageBox.Show($恭喜猜中了数字是{currentNumber}); else MessageBox.Show($没猜中你猜{guess}结果是{currentNumber}); } }4.2 定时器高级应用csharp// 多种定时器使用 // 1. Windows.Forms.TimerUI线程定时器 System.Windows.Forms.Timer uiTimer new System.Windows.Forms.Timer(); uiTimer.Interval 1000; uiTimer.Tick (s, e) { // 可以直接操作UI控件 label.Text DateTime.Now.ToString(); }; uiTimer.Start(); // 2. System.Threading.Timer线程池定时器 System.Threading.Timer threadTimer new System.Threading.Timer( state Console.WriteLine(定时执行), null, 0, 1000); // 3. System.Timers.Timer多功能定时器 System.Timers.Timer timer new System.Timers.Timer(1000); timer.Elapsed (s, e) Console.WriteLine(Elapsed); timer.AutoReset true; timer.Start();4.3 对话框使用csharp// 消息对话框 MessageBox.Show(消息内容, 标题, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); // 打开文件对话框 OpenFileDialog openFileDialog new OpenFileDialog(); openFileDialog.Filter 文本文件|*.txt|所有文件|*.*; openFileDialog.Title 选择文件; if (openFileDialog.ShowDialog() DialogResult.OK) { string filePath openFileDialog.FileName; string content File.ReadAllText(filePath); } // 保存文件对话框 SaveFileDialog saveFileDialog new SaveFileDialog(); saveFileDialog.Filter 文本文件|*.txt; if (saveFileDialog.ShowDialog() DialogResult.OK) { File.WriteAllText(saveFileDialog.FileName, content); } // 文件夹选择对话框 FolderBrowserDialog folderDialog new FolderBrowserDialog(); if (folderDialog.ShowDialog() DialogResult.OK) { string folderPath folderDialog.SelectedPath; }4.4 自定义控件csharp// 创建自定义控件 public class WatermarkTextBox : TextBox { private string watermarkText 请输入内容; private Color watermarkColor Color.Gray; public WatermarkTextBox() { this.Enter (s, e) { if (this.Text watermarkText) { this.Text ; this.ForeColor Color.Black; } }; this.Leave (s, e) { if (string.IsNullOrEmpty(this.Text)) { this.Text watermarkText; this.ForeColor watermarkColor; } }; this.Text watermarkText; this.ForeColor watermarkColor; } }五、综合实践文件管理器csharppublic partial class FileExplorerForm : Form { private TreeView treeView; private ListView listView; public FileExplorerForm() { InitializeComponent(); LoadDrives(); } private void LoadDrives() { foreach (DriveInfo drive in DriveInfo.GetDrives()) { TreeNode node new TreeNode(drive.Name); node.Tag drive.RootDirectory; treeView.Nodes.Add(node); } } private void LoadDirectory(string path) { listView.Items.Clear(); // 加载目录 foreach (string dir in Directory.GetDirectories(path)) { ListViewItem item new ListViewItem(Path.GetFileName(dir)); item.ImageIndex 0; // 文件夹图标 item.Tag dir; listView.Items.Add(item); } // 加载文件 foreach (string file in Directory.GetFiles(path)) { ListViewItem item new ListViewItem(Path.GetFileName(file)); item.ImageIndex 1; // 文件图标 item.Tag file; listView.Items.Add(item); } } }总结通过这四天的学习我们掌握了IO文件操作文件和目录的基本操作、文本和二进制文件读写多线程编程线程创建、线程安全、Task异步编程窗体应用窗体设计、控件使用、窗体间导航高级窗体定时器应用、猜数字游戏实现、对话框使用这些知识是C#桌面应用开发的基础掌握它们能够开发出功能完善的Windows应用程序。在实际开发中需要根据具体需求选择合适的IO操作方式、线程模型和窗体设计模式以提高程序的性能和用户体验。实践建议尝试开发一个完整的文件管理器实现多线程下载器开发带有实时时钟和倒计时的应用程序练习窗体间的数据传递和导航持续练习和项目实践是掌握这些知识的关键。

更多文章