kosnkov
kosnkov

Reputation: 5941

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

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;
    }
}

Upvotes: 0

Views: 573

Answers (1)

Christoph Fink
Christoph Fink

Reputation: 23103

The reason for that is you're using block inside ReadAllLines.

At the end of that block the StreamReader is disposed and that also disposes the underlying FileStream.

To avoid that you can pass leaveOpen = true to the StreamReader (last added true, see HERE):

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

Upvotes: 6

Related Questions