我需要读取可能被锁定的Windows文件,但我不想创建任何类型的锁,以防止其他进程写入该文件.
另外,即使文件被锁定以供独家使用,我也想看看里面有什么.
虽然这不是我的确切用例,但请考虑如何在使用和装载时读取SQL/Exchange日志或数据库文件.我不想导致腐败,但我仍然希望看到文件的内部并阅读它.
我有一个大致这样做的程序:
问题是,在从第4步到第1步之后,它无法读取文件说它正被另一个进程使用.
我收到错误:
未处理的异常:System.IO.IOException:进程无法访问文件'c:\ test.xml',因为它正由另一个进程使用.
什么出错了?我的程序的第1步的读者是否仍然打开文件,或者是访问该文件的完全不同的进程,还是filewatcher在从4移动到步骤1之后仍在观看文件,尽管将标志设置为false?
代码片段只是应该将字符串写入名为“all_results.txt”的文本文件中。我在 File.WriteAllText 中实现时出错。在网上搜索解决方案后,我尝试使用 FileStream 和 StreamWriter 作为替代品。问题仍然存在。
它给了我:
IOException 未处理:进程无法访问文件“C:\Users\MadDebater\Desktop\ConsoleTest1\ConsoleTest\bin\Debug\all_results.txt”,因为它正在被另一个进程使用。
奇怪的是,错误是任意发生的。它可能是在第 3 次循环期间或第 45 次循环期间发生错误。我提供了该类的完整代码,以防问题比看起来更严重。我确信这与我的病毒扫描程序或类似的东西无关。
try
{
using (FileStream stream = new FileStream(@"all_results.txt", FileMode.Create)) // Exception here
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(result);
writer.Dispose();
writer.Close();
}
stream.Dispose();
stream.Close();
}
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
Run Code Online (Sandbox Code Playgroud)
即使我尝试这样做,它仍然失败。
try
{
File.WriteAllText(@"all_results.txt", result); // Exception here
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
以下是该类的完整代码。它的目的是接收 Twitter 推文列表,并使用贝叶斯分类将它们一一分类。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BayesClassifier;
using …Run Code Online (Sandbox Code Playgroud) 我正在尝试读取某个程序正在使用的所有日志文件行。
当我尝试这样做时,我收到异常:
System.IO.IOException was unhandled : file used by another process
Run Code Online (Sandbox Code Playgroud)
所以我在网上搜索并找到了许多解决方案:
C# 异常。另一个进程
正在使用文件 读取另一个进程正在使用的日志
文件 在 C# 中读取锁定文件的侵入性最小的方法是什么(可能在不安全模式下)?
C#进程无法访问文件''',因为它正在被另一个进程使用
文件正在被另一个进程使用
http://coding.infoconex.com/post/2009/04/21/How-do-I-open -a-file-that-is-in-use-in-C
常见的解决方案是使用using包装FileStream和添加FileShare.ReadWrite.
我尝试了这些解决方案,但我仍然收到另一个进程正在使用该文件的异常。
在我下面的代码中,我打开文件D:\process.log以使用该文件(用于测试),然后尝试打开该文件。
例外是在行:
using (FileStream fileStream = File.Open(i_FileNameAndPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
Run Code Online (Sandbox Code Playgroud)
代码:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
DialogResult dialogResult = openFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
listView.Items.Clear();
File.Open(@"D:\process.log", FileMode.Open); //make the file being used …Run Code Online (Sandbox Code Playgroud)