Search code examples
c#pathstreamreader

Can you get file path from StreamReader object?


Is it possible to get the path that was used in the StreamReader constructor from the StreamReader object?

        using (StreamReader fileStream = new StreamReader(filePath))
        {
            string path = fileStream.???
        }

Solution

  • StreamReader exposes the stream from which it's reading via the BaseStream property. If the reader's stream is a FileStream, you can use its Name property to get the path of the file.

    using (StreamReader reader = new StreamReader(filePath))
    {
        string path = (reader.BaseStream as FileStream)?.Name;
    }
    

    Note: I renamed the variable to prevent possible confusion, since it IS a reader that HAS a stream.

    In this contrived example, it's obvious that it's a FileStream but the type test is necessary if you have a method that's taking a StreamReader.

    That said, you're causing the abstraction to leak by doing this. If you need to know the file name, you should explicitly require the file name or a FileStream instance.