File类、FileInfo类、Directory类、DirectoryInfo类
File类、Directory类,都是静态类,可以直接使用类名
FileInfo类、DirectoryInfo类,都是动态类,需要new对象,通过对象来操作
【文件的创建、复制、移动、删除】using System.IO;
//判断文件是否存在 File.Exists("C:\\test.txt"); FileInfo f = new FileInfo("C:\\test.txt"); if (f.Exists) { } //创建文件,删除文件(Create换成Delete) File.Create("C:\\test.txt"); FileInfo f = new FileInfo("C:\\test2.txt"); f.Create(); //复制文件 File.Copy("C:\\test.txt", "D:\\newTest.txt"); FileInfo f = new FileInfo("C:\\test2.txt"); f.CopyTo("D:\\newTest.txt"); //移动文件 File.Move("C:\\test.txt", "D:\\newTest.txt"); FileInfo f = new FileInfo("C:\\test2.txt"); f.MoveTo("D:\\newTest.txt");
【文件基本信息】
Name,文件名
FullName,完整目录(包括文件名)
DirectoryName,路径
IsReadOnly,是否只读
CreationTime,创建时间
Length,大小
private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog()==DialogResult.OK) { textBox1.Text = openFileDialog1.FileName; //显示文件名 FileInfo info = new FileInfo(openFileDialog1.FileName); MessageBox.Show(string.Format("文件名:{0} \n完整路径:{1} \n创建时间:{2} \n大小:{3}字节", info.Name, info.FullName, info.CreationTime, info.Length)); } }
【文件夹的创建、移动、删除】
//判断文件夹是否存在 Directory.Exists("C:\\Test"); DirectoryInfo f = new DirectoryInfo("C:\\Test"); if (f.Exists) { } //创建文件夹 Directory.CreateDirectory("C:\\Test"); DirectoryInfo f = new DirectoryInfo("C:\\Test"); f.Create(); //移动文件夹 Directory.Move("C:\\Test", "C:\\newTest"); //注意,不同磁盘间无法移动 DirectoryInfo f = new DirectoryInfo("C:\\Test"); f.MoveTo("C:\\newTest"); //删除文件夹 Directory.Delete("C:\\Test"); //注意,必须是空文件夹 DirectoryInfo f = new DirectoryInfo("C:\\Test"); f.Delete(true); //全部删除,包括子文件夹
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2017-05-04 数组、结构体、联合体、枚举类型、类型转换