c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件

c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件


问题描述:c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件,在IO处理上遇到了无法操作的问题。

文件“D:\log.txt”正由另一进程使用,因此该进程无法访问该文件。

log.txt是一个日志文件,不定时都可能由另外的程序对它进行日志记录写入操作。

今需要对日志文件读取出来,显示在日志查询里,需要用到了IO流。

1、 FileStream fs = File.OpenRead(url);
StreamReader sr = new StreamReader((System.IO.Stream)fs, System.Text.Encoding.Default);

错误提示:文件“D:\Log\Cargoabc\logfilecargoabc.txt”正由另一进程使用,因此该进程无法访问该文件。

2、StreamReader sr = File.OpenText(url);

错误提示:错误提示:文件“D:\Log\Cargoabc\logfilecargoabc.txt”正由另一进程使用,因此该进程无法访问该文件。

3、 FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);

正确读取。

总结:

这样的情况,不单要与只读方式打开txt文件,而且,需要共享锁。还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作。

原文链接https://blog.csdn.net/superhoy/article/details/7931234

C#中,要以管理员权限读写文件,可以使用以下代码片段: ``` using System; using System.Security.Principal; public static bool HasAdminRights() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } public static void WriteToFile(string filePath, string content) { if (HasAdminRights()) { // 以管理员权限直接写入文件 System.IO.File.WriteAllText(filePath, content); } else { // 创建一个以管理员权限运行的进程 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; startInfo.Arguments = $"\"{filePath}\" \"{content}\""; startInfo.Verb = "runas"; System.Diagnostics.Process.Start(startInfo); } } public static string ReadFromFile(string filePath) { if (HasAdminRights()) { // 以管理员权限直接读取文件内容 return System.IO.File.ReadAllText(filePath); } else { // 创建一个以管理员权限运行的进程 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; startInfo.Arguments = $"\"{filePath}\""; startInfo.Verb = "runas"; System.Diagnostics.Process.Start(startInfo); // 等待进程完成后再读取文件内容 System.Threading.Thread.Sleep(2000); return System.IO.File.Exists(filePath) ? System.IO.File.ReadAllText(filePath) : null; } } ``` 使用上述代码,你可以调用`WriteToFile`方法以管理员权限写入文件,调用`ReadFromFile`方法以管理员权限读取文件内容。如果当前用户已经具有管理员权限,则直接进行文件操作;否则,会弹出UAC提示框,用户需要选择以管理员身份运行程序,然后在程序中进行文件操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值