Reputation: 289
In C#, how do you grab the name or path of the streamreader
ie
filein = new StreamReader(@"C:\ee\fff\Desktop\spreadtool\test.csv");
and now I want to regex on the path, how do I reference the above. I know filestreamer has a getname() method but does streamreader? I looked it up and it doesn't seem to have one.
Upvotes: 4
Views: 5411
Reputation: 134065
Whereas it's true that a StreamReader
is not necessarily reading from a file, if it is reading from a file then the BaseStream
derives from FileStream
, and you can get the file name from that. The example below shows how to do it.
var filein = new StreamReader(filename);
string name = null;
if (filein.BaseStream is FileStream)
{
name = (filein.BaseStream as FileStream).Name;
}
Upvotes: 8
Reputation: 131676
You don't mention why you want to access the path through the reader, so I'll assume you want to pass "something" to another method, check whether it's a specific type based on its path and then read it.
You can use FileInfo to pass around the file's information including its full path, size, extension etc, and FileInfo.OpenText() to open a StreamReader on it, eg:
var fileInfo=new FileInfo(@"c:\path\to\my\file.csv");
....
using(var reader=fileInfo.OpenText())
{
var line=reader.ReadLine();
....
}
This way you avoid strange casts to FileStream, or having to open the StreamReader (locking the file) just to pass the name around.
Upvotes: 1
Reputation: 7951
StreamReader does not have a property that contains the FilePath from which it was created. It may not be created from a file at all (it can be created from a stream). If you want the path, you should store it in a string before you create the StreamReader
String file = @"C:\ee\ccc\Desktop\spreadtool\test.csv"
filein = new StreamReader(file);
String path = Path.GetDirectory(file);
Upvotes: 12
Reputation: 416081
What makes you so sure a given StreamReader has a name or path? You might be reading from the network, or a memorystream, serial connection, named pipe, database link... the list goes on and on.
Upvotes: 6