Create a FileService interface
in your Shared Code, create a new Interface, for instance, called IFileService.cs
public interface IFileService
{
void SavePicture(string name, Stream data, string location="temp");
}
Implementation Android
In your android project, create a new class called "Fileservice.cs".
Make sure it derives from your interface created before and decorate it with the dependency information:
[assembly: Dependency(typeof(FileService))]
namespace MyApp.Droid
{
public class FileService : IFileService
{
public void SavePicture(string name, Stream data, string location = "temp")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documentsPath = Path.Combine(documentsPath, "Orders", location);
Directory.CreateDirectory(documentsPath);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath , FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
}
}
Implementation iOS
The implementation for iOS is basically the same:
[assembly: Dependency(typeof(FileService))]
namespace MyApp.iOS
{
public class FileService: IFileService
{
public void SavePicture(string name, Stream data, string location = "temp")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documentsPath = Path.Combine(documentsPath, "Orders", location);
Directory.CreateDirectory(documentsPath);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath , FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
}
}
In order to save your file, in your shared code, you call
DependencyService.Get<IFileService>().SavePicture("ImageName.jpg", imageData, "imagesFolder");
and should be good to go.