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(); //每一行的内容
}

 

 

 

 

--

posted @ 2023-10-25 08:57  船长华莱士  阅读(13)  评论(0编辑  收藏  举报