C#多线程访问FileStream文件提示已打开

System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)

这个方法打开文件的时候是以只读共享的方式打开的,但若此文件已被一个拥有写权限的进程打开的话,就无法读取了,

因此需要使用

System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite);

设置文件共享方式为读写,FileShare.ReadWrite,这样的话,就可以打开了


 
 

C# FileStream Lock. How to wait for a file to get released and lock safely.

FileStream has Lock and Unlo
Let's say we have a file - the one to be used with multiple processes. I start with an assumption that file gets Write locked to get changed. If that is not the case for you, then my approach will not work. So if it sounds reasonable for you, then see the solution.
public static void Lock(string path, Action<FileStream> action)
{
    var autoResetEvent = new AutoResetEvent(false);
 
    while(true)
    {
        try
        {
            using (var file = File.Open(path,
                                        FileMode.OpenOrCreate,
                                        FileAccess.ReadWrite,
                                        FileShare.Write))
            {
                action(file);
                break;
            }
        }
        catch (IOException)
        {
            var fileSystemWatcher =
                new FileSystemWatcher(Path.GetDirectoryName(path))
                        {
                            EnableRaisingEvents = true
                        };
 
            fileSystemWatcher.Changed +=
                (o, e) =>
                    {
                        if(Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
                        {
                            autoResetEvent.Set();
                        }
                    };
 
            autoResetEvent.WaitOne();
        }
    }
}

So as you can see, we do an infinite loop which exits only on non IOException or when the block finishes successfully.

To wait and not consume 100% CPU AutoResetEvent which gets Set by FileSystemWatcher.Changed event.

So the flow looks like that:

1) We try to open the file
2) If we have an IOException, we wait until the file gets changed
3) We try to open file again, if failed - wait again
4) If file opened successfully, we perform an action passed as a parameter

You should carefully handle IOException inside your action. See the example:

FileLocker.Lock(@"c:\file",
        (f) =>
            {
                try
                {
                    f.Write(buf, 0, buf.Length);
                }
                catch(IOException ioe)
                {
// handle IOException
                }
            });

If you have any ideas on how to improve the solution, feel free to comment.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值