内容更改时读取共享文件 [英] Shared file read when content change

查看:81
本文介绍了内容更改时读取共享文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

创建一个文件监视程序,当内容更改时,我想在该文件监视程序中读取文件的最后一行.在这方面做了些什么.

Hi all,

Create a file watcher where I want to read the last line of the file when content is changes. Did something line this.

case WatcherChangeTypes.Changed:
	Console.WriteLine(string.Format("File {0} has been modified\r\n", e.FullPath));

    using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
		using (StreamReader sr = new StreamReader(fs))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                if (sr.EndOfStream)
                {
                    Console.WriteLine(line);
                }
            }
            sr.Close();
        }
        fs.Close();
    }

	break;



卡在两件事上,我找不到解决办法.每次更改内容时, changed 事件都会触发两次.

另一件事是文件有时以共享方式读取时出现错误,该错误是该进程由于另一个进程正在使用该文件而无法访问该文件"C:\ test_file.txt".我的测试方式是,注册文件查看器,在记事本中打开文件,添加一些内容并保存.

知道为什么会这样吗?



Stuck with two thing that I cannot find a solution. Each time when the content is changed the changed event fired twice.

The other thing is event the file read in shared mode when sometimes it gives the error that The process cannot access the file ''C:\test_file.txt'' because it is being used by another process. How I test this was, register the file watcher, open the file in notepad add some content and save.

Any idea why this is really happen?

推荐答案

好,您的问题分为两部分.首先,由于实际上是如何保存文件的,因此双重事件是正常现象.在这方面,记事本实际上是一个有问题的应用程序.您可以在此处找到有关此问题以及如何防止它的更多信息:

http://stackoverflow.com/questions/449993/vb-net-filesystemwatcher-multiple-更改事件 [ ^ ]

至于正在使用的文件,是因为确实如此. :-)好,抱歉,我知道那不能解决您的问题.我相信您的问题是您需要将FileShare模式更改为ReadWrite.这是一个解决该问题的堆栈溢出问题:

http://stackoverflow.com/questions/4400517/how-can-i-read-a-file-even-when-getting-an-in-use-by-another-process-exception [
OK, there are two parts to your question. First, the double-event is a normal occurance because of how the files are actually saved. Notepad is actually a problem application in this regards. You can find out more information about this and how to prevent it by going here:

http://stackoverflow.com/questions/449993/vb-net-filesystemwatcher-multiple-change-events[^]

As for the file being in use, that is because it is. :-) OK, sorry, I know that doesn''t solve your problem. I believe your issue is that you need to change your FileShare mode to ReadWrite. Here is a Stack Overflow question that addresses that:

http://stackoverflow.com/questions/4400517/how-can-i-read-a-file-even-when-getting-an-in-use-by-another-process-exception[^]


这篇关于内容更改时读取共享文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆