news 2026/7/7 19:27:05

C#文件操作大全,操作文件有这些都够了

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
C#文件操作大全,操作文件有这些都够了

操作文件和文件夹是程序开发中常用,无论是C/S和B/S都会存在操作文件的需求,比如上传新闻图片按日期创建文件夹,用文本文件存储用户信息等。下面介绍28种文件操作的方法,希望对大家的开发有所帮助

1.创建文件夹

//using System.IO;Directory.CreateDirectory(path);

2.创建文件

//using System.IO;File.Create(path);

3.删除文件

//using System.IO;File.Delete(path);

4.删除文件夹

//using System.IO;Directory.Delete(path);

5.删除一个目录下所有的文件夹

//using System.IO;foreach (string dirStr in Directory.GetDirectories(path)){ DirectoryInfo dir = new DirectoryInfo(dirStr); ArrayList folders=new ArrayList(); FileSystemInfo[] fileArr = dir.GetFileSystemInfos();for (int i = 0; i < folders.Count; i++) { FileInfo f = folders[i] as FileInfo;if (f == null) { DirectoryInfo d = folders[i] as DirectoryInfo; d.Delete(); } }}

6.清空文件夹

//using System.IO;Directory.Delete(path,true);Directory.CreateDirectory(path);

7.读取文件

//using System.IO;StreamReader s = File.OpenText(path1);string str2 = null;while ((str2 = s.ReadLine()) != null){ }s.Close();

8.写入文件

//using System.IO;FileInfo f = new FileInfo(str);StreamWriter w = f.CreateText();w.WriteLine(ReadOnlySpan);w.Close();

9.写入随机文件

//using System.IO;byte[] dataArray = new byte[100000];//new Random().NextBytes(dataArray);using(FileStream FileStream = new FileStream(path, FileMode.Create)){// Write the data to the file, byte by byte.for(int i = 0; i < dataArray.Length; i++){ FileStream.WriteByte(dataArray[i]); }// Set the stream position to the beginning of the file. FileStream.Seek(0, SeekOrigin.Begin);// Read and verify the data.for(int i = 0; i < FileStream.Length; i++){if(dataArray[i] != FileStream.ReadByte()){ //写入数据错误return; } }//"数据流"+FileStream.Name+"已验证"}

10.读取文件属性

//using System.IO;FileInfo f = new FileInfo(path);//f.CreationTime,f.FullNameif((f.Attributes & FileAttributes.ReadOnly) != 0){ path2}else{ path3}

11.写入属性

//using System.IO;FileInfo f = new FileInfo(path);//设置只读f.Attributes = myFile.Attributes | FileAttributes.ReadOnly;//设置可写f.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly; 12.枚举一个文件夹中的所有文件夹//using System.IO;foreach (string path2 in Directory.GetDirectories(path)){ path3}

13.复制文件夹

string path = (path2.LastIndexOf("\") == path2.Length - 1) ? path2 : path2+"\";string parent = Path.GetDirectoryName(path);Directory.CreateDirectory(path + Path.GetFileName(path));DirectoryInfo dir = new DirectoryInfo((path.LastIndexOf("\") ==path.Length - 1) ? path1 : path1 + "\");FileSystemInfo[] fileArr = dir.GetFileSystemInfos();Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());while (Folders.Count>0){ FileSystemInfo tmp = Folders.Dequeue(); FileInfo f = tmp as FileInfo;if (f == null) { DirectoryInfo d = tmp as DirectoryInfo; Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));foreach (FileSystemInfo fi in d.GetFileSystemInfos()) { Folders.Enqueue(fi); } }else { f.CopyTo(f.FullName.Replace(parent, path)); }}

14.复制目录下所有的文件夹到另一个文件夹下

DirectoryInfo d = new DirectoryInfo(path);foreach (DirectoryInfo dirs in d.GetDirectories()){ Queue<FileSystemInfo> al = new Queue<FileSystemInfo>(dirs.GetFileSystemInfos());while (al.Count > 0) { FileSystemInfo temp = al.Dequeue(); FileInfo file = temp as FileInfo;if (file == null) { DirectoryInfo directory = temp as DirectoryInfo; Directory.CreateDirectory(path + directory.Name);foreach (FileSystemInfo fsi in directory.GetFileSystemInfos()) al.Enqueue(fsi); }else File.Copy(file.FullName, path + file.Name); }}

15.移动文件夹

string filename = Path.GetFileName(path); string path=(path2.LastIndexOf("\") == path2.Length - 1) ? path2 : path2 + "\";if (Path.GetPathRoot(path) == Path.GetPathRoot(path2)) Directory.Move(path, path + filename);else { string parent = Path.GetDirectoryName(path); Directory.CreateDirectory(path + Path.GetFileName(path1)); DirectoryInfo dir = new DirectoryInfo((path.LastIndexOf("\") == path1.Length - 1) ? path1 : path1 + "\"); FileSystemInfo[] fileArr = dir.GetFileSystemInfos(); Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());while (Folders.Count > 0) { FileSystemInfo tmp = Folders.Dequeue(); FileInfo f = tmp as FileInfo;if (f == null) { DirectoryInfo d = tmp as DirectoryInfo; DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path)); dpath.Create();foreach (FileSystemInfo fi in d.GetFileSystemInfos()) { Folders.Enqueue(fi); } }else { f.MoveTo(f.FullName.Replace(parent, path)); } } Directory.Delete(path, true); }

16.移动目录下所有的文件夹到另一个目录下

string filename = Path.GetFileName(path);if (Path.GetPathRoot(path) == Path.GetPathRoot(path2))foreach (string dir in Directory.GetDirectories(path1)) Directory.Move(dir, Path.Combine(path2,filename));else {foreach (string dir2 in Directory.GetDirectories(path1)) { string parent = Path.GetDirectoryName(dir2); Directory.CreateDirectory(Path.Combine(path2, Path.GetFileName(dir2))); string dir = (dir2.LastIndexOf("\") == dir2.Length - 1) ? dir2 : dir2 + "\"; DirectoryInfo dirdir = new DirectoryInfo(dir); FileSystemInfo[] fileArr = dirdir.GetFileSystemInfos(); Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dirdir.GetFileSystemInfos());while (Folders.Count > 0) { FileSystemInfo tmp = Folders.Dequeue(); FileInfo f = tmp as FileInfo;if (f == null) { DirectoryInfo d = tmp as DirectoryInfo; DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path2)); dpath.Create();foreach (FileSystemInfo fi in d.GetFileSystemInfos()) { Folders.Enqueue(fi); } }else { f.MoveTo(f.FullName.Replace(parent, path2)); } } dirdir.Delete(true); } }

18.复制文件

//using System.IO;File.Copy(path1,path2);

19.复制一个文件夹下所有的文件到另一个目录

//using System.IO;foreach (string fileStr in Directory.GetFiles(path1)) File.Copy((path1.LastIndexOf("\") == path1.Length - 1) ? path1 +Path.GetFileName(fileStr): path1 + "\"+Path.GetFileName(fileStr),(path2.LastIndexOf("\\") == path2.Length - 1) ? path2 +Path.GetFileName(fileStr): path2 + "\"+Path.GetFileName(fileStr));

20.提取扩展名

//using System.IO;string path2=Path.GetExtension(path1);

21.提取文件名

//using System.IO;string path2=Path.GetFileName(path1);

22.提取文件路径

//using System.IO;string path2=Path.GetDirectoryName(path1);

23.替换扩展名

//using System.IO;File.ChangeExtension(path1,path2);

24.追加路径

//using System.IO;string path3=Path.Combine(path1,path2);

25.移动文件

//using System.IO;File.Move(path1,path2+"\"+file.getname(path1));

26.移动一个文件夹下所有文件到另一个目录

foreach (string fileStr in Directory.GetFiles(path1)) File.Move((path1.LastIndexOf("\") == path1.Length - 1) ? path1 +Path.GetFileName(fileStr): path1 + "\"+Path.GetFileName(fileStr),(path2.LastIndexOf("\\") == path2.Length - 1) ? path2 +Path.GetFileName(fileStr): path2 + "\"+Path.GetFileName(fileStr));

27.指定目录下搜索文件

string fileName=path1;string dirName=path2; DirectoryInfo dirc=new DirectoryInfo(dirName);foreach(FileInfo file in dirc.GetFiles()) {if(file.Name.IndexOf(fileName)>-1)return file.FullName; }foreach(DirectoryInfo dir in dirc.GetDirectories()) { return GetFile(fileName,dir.FullName); }return"找不到指定的文件"; }

28.获得当前路径

string path=Environment.CurrentDirectory;

你还有哪些文件操作的方法,欢迎留言。

版权声明:本文来源于网友收集或网友提供,仅供学习交流之用,如果有侵权,请转告版主或者留言,本公众号立即删除。

- EOF -

技术群:添加小编微信dotnet999

公众号:dotnet讲堂

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/7 20:04:48

掌握二维码生成神器:从入门到精通的完整指南

掌握二维码生成神器&#xff1a;从入门到精通的完整指南 【免费下载链接】node-qrcode qr code generator 项目地址: https://gitcode.com/gh_mirrors/no/node-qrcode 在数字化时代&#xff0c;二维码已成为连接线上线下的重要桥梁。无论你是开发者需要在应用中集成二维…

作者头像 李华
网站建设 2026/7/7 8:32:08

QQ 报错 0x80010001?文件丢失不用慌,注册表清理 + 重装搞定!

日常办公沟通、生活联络都离不开 QQ&#xff0c;可突然弹出的 “软件已被破坏或部分文件丢失” 提示&#xff08;错误码 0x80010001&#xff09;总能让人措手不及。明明之前还能用&#xff0c;毫无征兆就无法打开&#xff0c;尝试直接卸载重装后问题依旧 —— 残留的注册表垃圾…

作者头像 李华
网站建设 2026/7/7 8:53:41

用与球形粒子散射的MIE解

光的散射是最基本的光效应之一。对于大小与光的波长相当的散射粒子&#xff0c;例如空气中的液滴或气态污染物&#xff0c;需要进行精确的处理才能建立足够精确的模型。米氏解&#xff0c;也称为洛伦兹-米氏解&#xff0c;或米氏散射&#xff0c;已在VirtualLab Fusion中用于研…

作者头像 李华
网站建设 2026/7/7 18:17:36

不会设计问卷?百考通AI平台3分钟生成专业调研工具!

https://www.baikao tongai.com/wj 还在为毕业论文或市场调研的问卷设计发愁&#xff1f;不知道问题该怎么问才科学&#xff1f;选项如何设置才不带偏见&#xff1f;结构怎样安排才能提高回收率和数据质量&#xff1f;别再熬夜翻教程、反复修改了&#xff01;百考通全新推出的…

作者头像 李华
网站建设 2026/7/6 12:48:33

一句话生成专业问卷?百考通AI平台让调研“零门槛”!

https://www.baikao tongai.com/wj 还在为设计问卷绞尽脑汁&#xff1f;担心问题有引导性、选项不完整、结构混乱&#xff0c;导致数据无效&#xff1f;别再让这些细节拖垮你的研究或项目&#xff01;百考通全新推出的AI问卷设计平台&#xff08;https://www.baikao tongai.co…

作者头像 李华