Read file in Shared Library Xamarin c#

前端 未结 2 1743
花落未央
花落未央 2021-01-24 08:21

I have saved some .json files in the shared library.

I have managed to read just fine in iOS by the code

string fileName = $\"Files/file_name.json\";

v         


        
相关标签:
2条回答
  • 2021-01-24 08:36

    Are these files static (as in, they are part of the installation package), or are they saved by the application at runtime?

    If they are static, you need to put them in different places depending on the platform.

    For iOS you put the files in Resources, with a build type of BundleResource and access them with NSBundle.MainBundle.PathForResource.

    For Android, the files go in Assets, with a build type of AndroidAsset, and access them with Assets.Open.

    This page gives you more details.

    0 讨论(0)
  • 2021-01-24 08:50
    1. Add your "shared" file to your solution (in a folder within your PCL/NetStd/Shared project is fine, just set the build type to None).

    2. In your Android project, create a link to the file in the Assets with a build type of AndroidAsset.

    3. In your iOS project, create a link to the file with a build type of BundleResource.

    Android Example:

      <ItemGroup>
        <AndroidAsset Include="..\Forms_30\her.png">
          <Link>Assets\her.png</Link>
        </AndroidAsset>
      </ItemGroup>
    

    iOS Example:

      <ItemGroup>
        <BundleResource Include="..\Forms_30\her.png">
          <Link>her.png</Link>
        </BundleResource>
     </ItemGroup>
    

    Note: You can manually edit the .csproj or perform a drop/drop from Finder/Explorer using the starting location of the file in your PCL/NetStd library but make you select create a link when you drop the file.

    Now you can either use your own platform-dependent code via DI or use Xamarin.Essentials to access these read-only app bundled files from your PCL/NetStd library.

    Xamarin.Essentials

    using (var stream = await FileSystem.OpenAppPackageFileAsync("her.png"))
    {
         ~~~
    }
    
    0 讨论(0)
提交回复
热议问题