Getting Original Path from FileStream

45,198

Solution 1

The FileStream's Name property.

See documentation in MSDN

Solution 2

You can use fs.Name to get the path.

Solution 3

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();
Share:
45,198

Related videos on Youtube

Admin
Author by

Admin

Updated on July 08, 2020

Comments

  • Admin
    Admin almost 4 years

    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)
    {
    }
    
  • Admin
    Admin almost 15 years
    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.
  • Adrian Carr
    Adrian Carr about 8 years
    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.
  • Hi-Angel
    Hi-Angel about 8 years
    @AdrianCarr because the manual has example whilst the answer not 😛
  • Andrei Orlov
    Andrei Orlov about 4 years
    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.