C# 文件与目录的基本操作(System.IO)
1. 文件操作
/// <summary>
/// 文件读写操作
/// 为简化代码供大家学习,暂不考虑捕捉异常
/// </summary>
public partial class TestIO : DevComponents.DotNetBar.Office2007Form
{
public TestIO()
{
InitializeComponent();
}
/// <summary>
/// 创建文件
/// </summary>
private void btnCreateFile_Click(object sender, EventArgs e)
{
string path = Application.StartupPath + @"\Test.txt";
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("This is a test file.");
sw.WriteLine("This is second line.");
sw.Close();
fs.Close();
// 也可以这样创建 StreamWriter
// StreamWriter sw = File.CreateText(path);
}
/// <summary>
/// 读取文件
/// </summary>
private void btnReadFile_Click(object sender, EventArgs e)
{
string path = Application.StartupPath + "\\Test.txt";
textBoxX1.Text = string.Empty;
if (File.Exists(path))
{
FileStream fs = new FileStream(path, FileMode.Open);
StreamReader sr = new StreamReader(fs);
// 也可以这样创建 StreamReader
// File.OpenText(path);
string str = string.Empty;
while (true)
{
str = sr.ReadLine();
if (!string.IsNullOrEmpty(str))
{
textBoxX1.Text += str + "\r\n";
}
else
{
sr.Close();
fs.Close();
break;
}
}
}
else
{
MessageBox.Show("指定的路径下不存在此文件!");
}
}
/// <summary>
/// 追加文件内容
/// </summary>
private void btnAppendFile_Click(object sender, EventArgs e)
{
string path = Application.StartupPath + "\\Test.txt";
FileStream fs = new FileStream(path, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
// 也可以这样创建 StreamReader
// StreamWriter sw = File.AppendText(path);
sw.WriteLine("This is three line.");
sw.Close();
fs.Close();
}
/// <summary>
/// 复制文件
/// </summary>
private void btnCopyFile_Click(object sender, EventArgs e)
{
string oldPath = Application.StartupPath + "\\Test.txt";
string newPath = Application.StartupPath + "\\TestClone.txt";
File.Copy(oldPath, newPath);
}
/// <summary>
/// 删除文件
/// </summary>
private void btnDeleteFile_Click(object sender, EventArgs e)
{
string path = Application.StartupPath + "\\TestClone.txt";
File.Delete(path);
}
/// <summary>
/// 移动文件
/// </summary>
private void btnMoveFile_Click(object sender, EventArgs e)
{
string oldPath = Application.StartupPath + "\\Test.txt";
// 移动文件的同时也可以使用新的文件名
string newPath = "d:\\NewTest.txt";
File.Move(oldPath, newPath);
}
/// <summary>
/// 创建目录
/// </summary>
private void btnCreateDirectory_Click(object sender, EventArgs e)
{
string path1 = "d:\\Jason1";
// 创建目录 Jason1
DirectoryInfo dDepth1 = Directory.CreateDirectory(path1);
// dDepth2 指向 dDepth1 创建的子目录 Jason2
DirectoryInfo dDepth2 = dDepth1.CreateSubdirectory("Jason2");
// 设置应用程序当前的工作目录为 dDepth2 指向的目录
Directory.SetCurrentDirectory(dDepth2.FullName);
// 在当前目录创建目录 Jason3
Directory.CreateDirectory("Jason3");
}
private void btnDeleteDirectory_Click(object sender, EventArgs e)
{
string path = "d:\\Jason1";
DeleteDirectory(path);
}
/// <summary>
/// 删除目录及其所有子目录,文件
/// </summary>
private static void DeleteDirectory(string path)
{
if (Directory.Exists(path))
{
foreach (string str in Directory.GetFileSystemEntries(path))
{
if (File.Exists(str))
{
File.Delete(str);
}
else
{
DeleteDirectory(str);
}
}
Directory.Delete(path);
}
else
{
MessageBox.Show("该目录不存在!");
}
}
private void btnCopyDirectory_Click(object sender, EventArgs e)
{
string sourcePath = "d:\\Jason1";
string targetPath = "d:\\Jason2";
CopyDirectory(sourcePath, targetPath);
}
/// <summary>
/// 复制目录及其所有内容
/// </summary>
/// <param name="sourcePath">源目录</param>
/// <param name="targetPath">目标目录</param>
private void CopyDirectory(string sourcePath, string targetPath)
{
// 该字符用于在反映分层文件系统组织的路径字符串中分隔目录级别(msdn)
// 在windows系统下实质上是为目录路径加上"\\"
if (targetPath[targetPath.Length - 1] != Path.DirectorySeparatorChar)
{
targetPath += Path.DirectorySeparatorChar;
}
// 目标目录不存在则创建之
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// 获取文件系统(含目录和文件)
string[] fileList = Directory.GetFileSystemEntries(sourcePath);
foreach (string fileName in fileList)
{
if (Directory.Exists(fileName))
{
// Path.GetFileName(fileName) 可取出最后一个分级目录名或文件名
CopyDirectory(fileName, targetPath + Path.GetFileName(fileName));
}
else
{
// true 为可覆盖
File.Copy(fileName, targetPath + Path.GetFileName(fileName), true);
}
}
}
}
分类:
Winform开发技术
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构