xamarin.将数据附加到android 10中的文本文件(API 29)



我正在开发一个应用程序,该应用程序将当前日期作为文件名写入日志文件

例如:20200710.txt

之前的在android 10之前运行良好,但从android 10开始,代码不再在外部存储中写入文件。

所以我修改了android 10的代码,特别是

string logDir = "Documents/MyApp_Data/logs/";
Context context = MyApplication.Context;

ContentValues values = new ContentValues();
values.Put(MediaStore.MediaColumns.DisplayName, filename);
values.Put(MediaStore.MediaColumns.MimeType, "text/plain");   //file extension, will automatically add to file
values.Put(MediaStore.MediaColumns.RelativePath, logDir);
var uri = context.ContentResolver.Insert(MediaStore.Files.GetContentUri("external"), values);
Stream outputStream = context.ContentResolver.OpenOutputStream(uri, "rw");
outputStream.Write(Encoding.UTF8.GetBytes(message));
outputStream.Close();

上面的代码适用于android 10,但它正在创建多个日志文件,如果该文件已经存在,我想更新该文件。我没有办法检查文件是否存在,然后在现有文件中附加新数据。有人能告诉我吗?上面的代码是在Xamarin android中,但如果你有任何建议,将在android中工作,那么我会将该代码转换为Xamarin安卓

提前感谢

此代码更正(尤其是单词的大写/小写(vaibhav,并使用blackapps建议包含文本附加。可以写txt或json。很适合在Android 10+上在没有用户交互的情况下在持久文件夹(例如/storage/self/Downloads(中编写文本(实际上没有在11上测试,但应该可以(。

// filename can be a String for a new file, or an Uri to append it
fun saveTextQ(ctx: Context,
relpathOrUri: Any,
text: String,
dir: String = Environment.DIRECTORY_DOWNLOADS):Uri?{

val fileUri = when (relpathOrUri) {
is String -> {
// create new file
val mime =  if (relpathOrUri.endsWith("json")) "application/json"
else "text/plain"

val values = ContentValues()
values.put(MediaStore.MediaColumns.DISPLAY_NAME, relpathOrUri)
values.put(MediaStore.MediaColumns.MIME_TYPE, mime) //file extension, will automatically add to file
values.put(MediaStore.MediaColumns.RELATIVE_PATH, dir)
ctx.contentResolver.insert(MediaStore.Files.getContentUri("external"), values) ?: return null
}
is Uri -> relpathOrUri   // use given Uri to append existing file
else -> return null
}

val outputStream    = ctx.contentResolver.openOutputStream(fileUri, "wa") ?: return null

outputStream.write(text.toByteArray(charset("UTF-8")))
outputStream.close()

return fileUri  // return Uri to then allow append
}