After manually delete a file, and use FileOutputStream to create same name file, it will fail with "file exists" error?

aluzi liu 486 Reputation points
2022-07-19T10:55:47.003+00:00

My app will download file from server, and store it in folder:
/storage/emulated/0/Documents/MyFolder

Every time user download file, I will check if file already exists, if so, delete it, and create new one:

                    file = new Java.IO.File(filePath);  
                    if (file.Exists())  
                        file.Delete();  
  
                    FileOutputStream fileOutputStream = new FileOutputStream(new Java.IO.File(filePath));  
                    fileOutputStream.Write(data);  
                    fileOutputStream.Close();  
  

The code run perfect, BUT! If user goto other file-browser app, and delete this file manually, back to my app, download it again, it will error:
/storage/emulated/0/Documents/MyFolder/filename.docx: open failed: EEXIST (File exists)

I am 100% sure that this file is deleted(and recycle-bin is empty), what's the problem? How to fix it?

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-07-20T04:59:17.097+00:00

    Hello,​

    it will error:/storage/emulated/0/Documents/MyFolder/filename.docx: open failed: EEXIST (File exists)

    Did you run your application on the android 10 or later?

    For android 10, please add android:requestLegacyExternalStorage="true" in <Application> tag of AndroidManifest.xml

    For Android 11 or later, this issue is related to Android 11 storage limitation, if you want to delete/create external file path, you need to request following permission and Manage all files on a storage device.

       <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>  
    

    This permission needs request it. After that, you can execute the above code.

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.