I've been struggling to write a file to the internal storage. I want to save the file to such a location where the user can see it and read the file such as Mydocuments or in the Internal storage by creating a seperate folder for my app like whatsapp does. I also want the same scenario in iOS.
How do i do that? I have tried the FileSystem Helpers in Xamarin.Essentials and have also used the Environment.SpecialFolder but nothing seems to work. I am just trying to save a simple text file.
The links that I have tried..
https://learn.microsoft.com/en-us/xamarin/android/platform/files/
https://learn.microsoft.com/en-us/xamarin/essentials/file-system-helpers?context=xamarin%2Fandroid&tabs=android
NOTE: I am not interested in the External storage.
Do you want to store the data in these folders?
If so, for android, I make a dependenceService to achieve it.
For example, I want to write a .txt
file to Download
folder. I create intferface in PCL.
public interface IWirteService
{
void wirteFile(string FileName);
}
Execute it in the pcl Button click event.
private void Button_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IWirteService>().wirteFile("myfile.txt");
}
Then achieved it in the android platform.
[assembly: Xamarin.Forms.Dependency(typeof(WirteFileService))]
namespace XamarinFirebase.Droid
{
public class WirteFileService:IWirteService
{
void IWirteService.wirteFile(string FileName)
{
string text = "GFG is a CS portal.";
byte[] data = Encoding.ASCII.GetBytes(text);
string DownloadsPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
string filePath = Path.Combine(DownloadsPath, FileName);
File.WriteAllBytes(filePath, data);
}
}
}
Do not forget to add following permission and achieve runtime permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is running GIF.
For people who are searching for the answer. Please visit this link => https://stackoverflow.com/a/63777656/9048996
Here there is solution which helps to create a seperate directory in our internal storage or external if available. Then you can create your own files in that dedicated directory and the files are public and is visible to the user so that they can share them if required. The provided solution is only for android.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With