C# PCL Reading from File

Will Custode picture Will Custode · Mar 20, 2013 · Viewed 9.6k times · Source

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!

Answer

Matt Lacey picture Matt Lacey · Mar 20, 2013

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.