0

I am working on an application where app writes a log file with the currentdate as filename

Ex: 20200710.txt

The earlier was working fine before android 10 but from android 10 the code is no longer writing the file in the external storage.

So I have modified the code a bit for android 10 especially

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();

The above code is working for android 10 but it is creating multiple log files instead I want to update the file if the file already exists. I am not getting a way to check if the file exists then append new data in the existing file. Can someone please let me know? The above code is in Xamarin android but if you have any suggestion that will work in android then I will convert that code to Xamarin android

Thanks in advance

大陸北方網友
  • 3,696
  • 3
  • 12
  • 37
  • `var uri = context.ContentResolver.Insert(MediaStore.Files.GetContentUri("external")` You should remember that uri and use it the next times. And open the stream with "wa". – blackapps Oct 07 '20 at 09:58
  • But it is much simpler continue to use your old code: https://stackoverflow.com/questions/63842070/accessing-external-storage-in-android-api-29 – blackapps Oct 07 '20 at 10:01
  • Add the line `android:requestLegacyExternalStorage="true"` in manifest.xml – Lucas Zhang Oct 07 '20 at 11:34
  • @LucasZhang-MSFT - I have already tried this but not working. – Developer_vaibhav Oct 07 '20 at 11:46
  • Here is a similar issue https://forums.xamarin.com/discussion/comment/422638#Comment_422638 .You could check Leon's code on your side . It works on Android 10 . – Lucas Zhang Oct 08 '20 at 08:02

1 Answers1

0

This code corrects (especially words' upper/lower cases) vaibhav ones and use blackapps suggestion to include text append. Can write txt or json. Good to write text in persistent folders (e.g. /storage/self/Downloads) without user interaction on Android 10+ (actually not tested on 11, but should work).

    // 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
    }
albaspazio
  • 121
  • 1
  • 6