47

Given a System.IO.FileStream object, how can I get the original path to the file it's providing access to?

For example, in the MyStreamHandler() function below, I want to get back the path of the file that created the FileStream:

public static void Main() 
{
    string path = @"c:\temp\MyTest.txt";
    FileStream fs = File.Create(path));

    MyStreamHandler(fs);
    MyOtherStreamHandler(fs);

    fs.Close();
    fs.Dispose();
}

private static void MyStreamHandler(FileStream fs)
{
    // Get the originating path of 'fs'
} 

private static void MyOtherStreamHandler(FileStream fs)
{
}

3 Answers3

86

The FileStream's Name property.

See documentation in MSDN

Yuriy Faktorovich
  • 62,163
  • 14
  • 99
  • 133
  • 10
    Thanks for answering what was apparently an RTFM-type question. I did actually, but it wasn't obvious to me that Name got the path. –  Jul 22 '09 at 14:35
  • 2
    I hate to say it, but why read the manual when you have StackOverflow? It's sooo much faster to find, with examples by people that use the technology. – Adrian Carr Feb 19 '16 at 03:52
  • 2
    @AdrianCarr because the manual has example whilst the answer not – Hi-Angel Apr 14 '16 at 14:50
  • FYI: If the absolute path is not known, this property returns a string similar to "[Unknown]". It's the case when FileStream was instantiated using SafeFileHandle. – Andrei Orlov Mar 05 '20 at 22:14
6

You can use fs.Name to get the path.

cakeforcerberus
  • 4,517
  • 5
  • 30
  • 42
1

Use FileInfo-Class for getting the path.

var fileStream = File.OpenRead(fileName);
var fileInfo = new FileInfo(fileName);

Settings.Default.ThePath = fileInfo.DirectoryName;
Settings.Default.Save();
AsH
  • 11
  • 2