C# PCL Reading from File

只愿长相守 提交于 2020-01-01 08:43:12

问题


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!


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/15528751/c-sharp-pcl-reading-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!