I have a code like this:
string filePath = Path.Combine(FileSystem.AppDataDirectory, "test.jpg");
if (File.Exists(filePath))
{
Debug.WriteLine("File Exist!");
try
{
File.Delete(filePath);
}
catch (Exception ex) {
Debug.WriteLine("Exception!");
}
}
else
{
Debug.WriteLine("File not exists!");
}
if(File.Exists(filePath))
{
Debug.WriteLine("File not deleted!");
}
// Output:
File Exist!
File not deleted!
I am writing an application for Android. I am trying to delete a file in the AppDataDirectory folder but I cannot delete it. I also do not receive any exception messages. I cannot understand this situation. (Although the AppDataDirectory folder does not require write permission, I have added the necessary permissions. Also, such a problem does not occur in the Windows application and the file is deleted). Can your help me with this issue? Thanks.
EDIT
I did some deep research on this. I think it's a problem with .Net Maui (.NET 8). (on Android).
My alternative solution was:
var file = new FileInfo(filePath);
file.Delete();
So the file can be deleted on Android too.
First of, the Path.Combine
will not create the file if it's not existed on the android. So I used the FileStream
to create it.
string filePath = Path.Combine(FileSystem.AppDataDirectory, "test.jpg");
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
{
}
And then, the File.Delete(filePath)
work well in my project. The output in my project:
// Output:
File Exist!
And I have used the Device File Explorer in the Android Studio to check the result: The file will be deleted after File.Delete(filePath)
excuted.
The environment I used: