So I'm writing a portable class library that targets .NET 4.5, Windows 8 and Windows Phone 8. I'm trying to read from a text file that is part of the project as build content. I see that StreamReader is available in PCL's but I can't seem to find out how to get the stream from a file, given a file path. If anyone could point me to the right structures I'd appreciate it. Also if you could give direction for XML files, too. I'm only reading text files right now, but I'm going to be working in XML later. Thanks!
-
can you give the StreamReader a Stream ? then the question is just "opening a file", which should be fine in either, no? The same would work fine for most XML APIs – Marc Gravell Mar 20 '13 at 16:05
-
I have a string that is a file path, but StreamReader takes in a stream (obviously). I'm asking how, in a PCL, do you turn a path into a Stream. – Will Custode Mar 20 '13 at 16:07
-
If it's possible to change the build action on your file to Embedded Resource, you could use the method given in the first answer [here](http://stackoverflow.com/questions/10963781/how-to-read-a-resource-file-within-a-portable-class-library). – SWalters Mar 20 '13 at 16:16
-
I have to keep it as content as it can be added after the project is built. – Will Custode Mar 20 '13 at 16:21
2 Answers
Portable class libraries allow you to work with namespaces and classes that exist in all the platforms that you're targeting.
.Net 4.5 (assuming you mean the full desktop-WinForms/WPF), Windows 8 and Windows Phone 8 all do file access very differently and have different files available to them. Where files can be accessed from also differs greatly: embedded content; embedded resources; isolated storage; shared folders; the full file system. These aren't all available on all the platforms you mention.
Short answer. You probably can't do what you're after.
File system access varies dramatically across platforms and typically has to be done differently for each platform.
What you can do is define an interface for file access (open, read, save, etc.) that your PCL can use and then create platform specific instances that you pass to the PCL as needed.

- 65,560
- 11
- 91
- 143
-
1Thanks, I hoped in such a high level construct as .NET this would not have been an issue. But I totally understand where the limitation comes from. Oh well, on to interfaces! Thanks again. – Will Custode Mar 21 '13 at 14:08
Matt is correct.
However, there are plugins to allow you to access files from PCL.
My library, MvvmCross provides one - https://github.com/slodge/MvvmCross/tree/vnext/Cirrious/Plugins/File
However... for what you are currently doing I think your best bet is @dsplaisted's Portable File Storage library - this is available via Nuget - http://nuget.org/packages/pclstorage - this is written by one of the PCL team from Microsoft - and it's a good fit for turning path's into Streams in PCLs

- 66,722
- 7
- 114
- 165