在Visual Studio和模拟器中使用MonoDroid,我试图将资产“db.sqlite”从assets文件夹复制到SD卡,以便我可以打开数据库进行读/写。
当我运行应用程序时,它会死掉。 MonoDroid没有给我任何调试信息。
string destPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.Personal), "db.sqlite");
if (!File.Exists(destPath))
using (Stream stream = Assets.Open("db.sqlite"))
{
stream.CopyTo(File.Create(destPath));
stream.Close();
}
答案 0 :(得分:2)
答案 1 :(得分:2)
尝试使用数据库文件.mp3扩展名保存文件,然后使用以下脚本将其复制到SD卡
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs());
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".mp3")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
答案 2 :(得分:0)
适用于我的代码(它递归复制文件或目录及所有子目录):
private void copy(string SourcePath){
string[] list = Assets.List(SourcePath);
if (list.Length > 0) {
Directory.CreateDirectory(AndroidResorces.GetDatabaseStorage() + "/" + SourcePath);
foreach (string dirPath in Assets.List(SourcePath)){
string newPath = SourcePath + "/" + dirPath;
copy(newPath);
}
}
else{
Assets.Open(SourcePath).CopyTo(new FileStream(AndroidResorces.GetDatabaseStorage() + "/" + SourcePath, FileMode.OpenOrCreate));
}
}
用法:copy(path_relative_to_assets_root);