user116592
user116592

Reputation:

Getting Original Path from FileStream

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)
{
}

Upvotes: 50

Views: 54141

Answers (3)

AsH
AsH

Reputation: 11

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();

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

The FileStream's Name property.

See documentation in MSDN

Upvotes: 91

cakeforcerberus
cakeforcerberus

Reputation: 4657

You can use fs.Name to get the path.

Upvotes: 7

Related Questions