在文件解锁并且可以读取和重命名之前,阻塞线程的最简单方法是什么?例如,.NET Framework中的某个地方是否存在WaitOnFile()?
我有一个服务,使用FileSystemWatcher查找要传输到FTP站点的文件,但文件创建事件在另一个进程写完文件之前触发.
理想的解决方案将有一个超时期限,因此线程在放弃之前不会永久挂起.
编辑:在尝试下面的一些解决方案后,我最终更改系统,以便所有文件写入Path.GetTempFileName(),然后执行File.Move()到最终位置.一旦FileSystemWatcher事件被触发,该文件就已经完成.
目标
我想按下GUI上的按钮并从远程计算机读取seclog.log文件(symantec AV日志),并将日志内容显示在我的应用程序中的富文本框中.
有用的东西
一切,但阅读日志文件
错误信息
System.IO.IOException was unhandled
Message=The process cannot access the file '\\HOSTNAME\C$\Program Files (x86)\Symantec\Symantec Endpoint Protection\seclog.log' because it is being used by another process.
Source=mscorlib
Run Code Online (Sandbox Code Playgroud)
码
//possible seclog paths
String seclogPath1 = @"\\\\" + target + "\\C$\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\seclog.log";
String seclogPath2 = @"\\\\" + target + "\\C$\\Program Files\\Symantec\\Symantec Endpoint Protection\\seclog.log";
//if seclog exists
if (File.Exists(seclogPath1))
{
//output.AppendText("file exists at " + seclogPath1);
//var seclogContent = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Stream stream = File.OpenRead(seclogPath1);
StreamReader …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)