There is no cross platform api can do this. You need to call the platform native code.
1. For the android:
Call the following code to get the Download folder (use download folder because there is no documents folder on android 10 and lower version), create file and write it.
#if ANDROIDvar path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;using (FileStream fileStream = new FileStream(Path.Combine(path, "test.log"), FileMode.Create)){ var data = Encoding.UTF8.GetBytes("this is log file"); await fileStream.WriteAsync(data, 0, data.Length);}#endif
In addition, the code above can run directly without any permission on android 11 and higher version. For the android 10 and lower vresion, you need to request the storage permission.
Add the permission and the android:requestLegacyExternalStorage="true"
(only used for android 10) in the AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true" android:requestLegacyExternalStorage="true"></application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/></manifest>
Request the permission at runtime:
if (Android.OS.Build.VERSION < Android.OS.BuildVersionCodes.R){ var status = Permissions.RequestAsync<Permissions.StorageWrite>();}
2. For the iOS
There is no public Documents folder on iOS. Every app has its own Docuemnts folder. And you can use the following code to create file and write it:
var path = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);using (FileStream fileStream = new FileStream(Path.Combine(path, "test.log"), FileMode.Create)){ var data = Encoding.UTF8.GetBytes("this is log file"); await fileStream.WriteAsync(data, 0, data.Length);}
In addition, if you want to the other users can access the file, please add the following key into the Info.plist:
<key>LSSupportsOpeningDocumentsInPlace</key><true/><key>UIFileSharingEnabled</key><true/>
Finally, please test it on the physical device, this can't work on the simulator.