简体   繁体   English

StreamReader释放文件锁定

[英]StreamReader release lock on file

Hi I found a problem that if I open a file with FileShare.None and then create StreamReader in static class after it read all lines it will also release the file 嗨,我发现一个问题,如果我用FileShare.None打开一个文件,然后在读取所有行后在静态类中创建StreamReader,它也会释放该文件

class Program
{
    static void Main(string[] args)
    {
        using (
            var fileStream = new FileStream(
                 @"SomeShareFolder\File.txt",
                FileMode.Open,
                FileAccess.Read,
                FileShare.None,
                512,
                FileOptions.None))
        {
            var lines = fileStream.ReadAllLines();
    //HERE THE FILE IS ALREADY RELESEAD so other process now if tries to open with FileStream and  FileShare.None there will not be any exception that file is locked
        }
    }
}

public static class FileStreamExtension
{
    public static List<string> ReadAllLines(this FileStream filestream, StringSplitOptions splitOption = StringSplitOptions.RemoveEmptyEntries)
    {
        var strings = new List<string>();

        using (var file = new StreamReader(filestream, Encoding.UTF8, true, 512))
        {
            string lineOfText;

            while ((lineOfText = file.ReadLine()) != null)
            {
                if (splitOption != StringSplitOptions.RemoveEmptyEntries || !string.IsNullOrEmpty(lineOfText))
                {
                    strings.Add(lineOfText);
                }
            }
        }

        return strings;
    }
}

The reason for that is you're using block inside ReadAllLines . 这样做的原因是您在ReadAllLines using block。

At the end of that block the StreamReader is disposed and that also disposes the underlying FileStream . 在该块的末尾,放置了StreamReader ,并且还放置了基础FileStream

To avoid that you can pass leaveOpen = true to the StreamReader (last added true , see HERE ): 为了避免这种情况,您可以将leaveOpen = true传递给StreamReader (最后添加的true ,请参见HERE ):

using (var file = new StreamReader(filestream, Encoding.UTF8, true, 512, true))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM