【发布时间】:2012-10-17 12:43:24
【问题描述】:
是否可以在引用类库的 monodroid 应用程序中从 monodroid 类库访问文件(使用构建操作“AndroidAsset”)?
我在类库中创建了一个“Assets”文件夹,并添加了一个带有构建操作“AndroidAsset”的文本文件,但从应用程序中我无法通过 Assets.Open("file.txt"); 访问它;
我希望类库和主应用程序中的资产可以以某种方式“合并”...
【问题讨论】:
是否可以在引用类库的 monodroid 应用程序中从 monodroid 类库访问文件(使用构建操作“AndroidAsset”)?
我在类库中创建了一个“Assets”文件夹,并添加了一个带有构建操作“AndroidAsset”的文本文件,但从应用程序中我无法通过 Assets.Open("file.txt"); 访问它;
我希望类库和主应用程序中的资产可以以某种方式“合并”...
【问题讨论】:
不——你不能从类库中访问资产——只能从主 exe 项目中访问。
这与 Java Android 项目的情况类似。
解决此问题的一种方法可能是改用嵌入式资源 - 请参阅我在 xamarin 论坛上提出的这个问题的答案 - http://forums.xamarin.com/discussion/186/is-there-a-cross-platform-way-to-include-string-resources-from-class-library-projects - 请注意,我还没有尝试过这个
【讨论】:
是否可以在引用类库的 monodroid 应用程序中从 monodroid 类库访问文件(使用构建操作“AndroidAsset”)?
是的。只需通过Context.Assets.Open“正常”访问它们。应用程序中只有一个资产来源,因此任何组件都可以访问任何和所有资产,前提是它们可以访问AssetManager 实例。
然而,这只是表面上你所要求的。图书馆项目可以使用Context.Assets 属性吗?当然,如果你提供一个Context 实例。
但是图书馆项目可以提供它自己的资产以包含在应用程序中吗?没有。
我在类库中创建了一个“Assets”文件夹,并添加了一个带有构建操作“AndroidAsset”的文本文件,但从应用程序中我无法通过 Assets.Open("file.txt"); 访问它;
图书馆项目不能提供将包含在更大的应用程序中的资产。 Java 也不支持这个,afaik。
【讨论】:
1 Build Action 是 AndroidAsset(属性)
2 复制到输出目录不要复制(属性)
3 将文件添加到 Assets 文件夹
var destinationPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "yourfilename.txt");
using (Stream source = Assets.Open("yourfilename.txt"))
using (var dest = System.IO.File.Create (destinationPath)) {
source.CopyTo (dest);
}
有时这仍然会失败,monodroid 错误。最好的办法是检查文件是否正确包含。
Load up Eclipse, in the device browser, you should see your simulator.
Go to the directory data/app/ download the file yourappname.apk
This is just a zip file, so change the extension to .zip and open the
zip archive. And goto the folder /assets and see if the file you are trying
to load is in there.
此外,如果您尝试从您的测试所用的物理设备上抓取文件,有些允许,有些则不允许。这是最容易在模拟器上测试的。
【讨论】:
可以从库中访问资产文件:
var sourcePath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
//var files = Directory.GetFiles(sourcePath);
var filePath = Path.Combine(sourcePath, "MyAssetFile.bin");
var content = File.ReadAllBytes(filePath);
【讨论】: