c# IO、文件相关
1. c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件
问题描述:
c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件,在IO处理上遇到了无法操作的问题
使用IO流如下
(1)
FileStream fs = File.OpenRead(url); StreamReader sr = new StreamReader((System.IO.Stream)fs, System.Text.Encoding.Default);
错误提示:文件“D:\xxx\xxx\xxx.txt”正由另一进程使用,因此该进程无法访问该文件
(2)
StreamReader sr = File.OpenText(url);
错误提示:错误提示:文件“D:\xxx\xxx\xxx.txt”正由另一进程使用,因此该进程无法访问该文件
(3)
FileStream fs = new FileStream($@"{AttriSave}\{AttriStage}\{AttriFilename}.txt, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
正确读取
这样的情况,不单要与只读方式打开txt文件,而且,需要共享锁。还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作
2. 获取磁盘列表
String[] drives = Environment.GetLogicalDrives();
using System.IO; DriveInfo[] allDirves = DriveInfo.GetDrives();
3. 获取文件名、目录、后缀、无后缀文件名、扩展名
转载于:C# 获取文件名、目录、后缀、无后缀文件名、扩展名 - 搬砖的L先生 - 博客园 (cnblogs.com)
string filePath = "C:\\1.txt"; string str = "获取文件的全路径:" + Path.GetFullPath(filePath); //-->C:1.txt str = "获取文件所在的目录:" + Path.GetDirectoryName(filePath); //-->C: str = "获取文件的名称含有后缀:" + Path.GetFileName(filePath); //-->1.txt str = "获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(filePath); //-->1 str = "获取路径的后缀扩展名称:" + Path.GetExtension(filePath); //-->.txt str = "获取路径的根目录:" + Path.GetPathRoot(filePath); //-->C:\
4. 读取文本文件并逐行遍历
string content = string.Empty;
FileStream fs = new FileStream("D:\direc1\direc2\1.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader textReader = new StreamReader(fs, System.Text.Encoding.Default);
while (null != (content = textReader.ReadLine()))
{
content = content.Trim().ToString(); //每一行的内容
}
5. 文件及文件夹遍历
// SearchOption.AllDirectories 搜索本文件夹和所有子目录 // 通配符"*.*" 也可以是 "*" // 遍历所有文件 var files = Directory.GetFiles(@"D:\Job", "*.*", SearchOption.AllDirectories); // 遍历所有文件夹 var dirs = Directory.GetDirectories(@"D:\Job", "*.*", SearchOption.AllDirectories); // 遍历所有文件夹和文件 var list = files.Union(dirs).OrderBy(s => s); // 遍历所有文件 var files1 = Directory.EnumerateFiles(@"D:\Job", "*.*", SearchOption.AllDirectories); // 遍历所有文件夹 var dirs1 = Directory.EnumerateDirectories(@"D:\Job", "*.*", SearchOption.AllDirectories); // 遍历所有文件 var files2 = new DirectoryInfo(@"D:\Job").GetFiles("*.*", SearchOption.AllDirectories); // 遍历所有文件夹 var dirs2 = new DirectoryInfo(@"D:\Job").GetDirectories("*.*", SearchOption.AllDirectories); // 遍历所有文件 var files3 = new DirectoryInfo(@"D:\Job").EnumerateFiles("*.*", SearchOption.AllDirectories); // 遍历所有文件夹 var dirs3 = new DirectoryInfo(@"D:\Job").EnumerateDirectories("*.*", SearchOption.AllDirectories);
--
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了