Reputation: 1
As System.IO.File is not available in Xamarin PCL, I have heard that the only way out of the problem of writing JSON file is to use Streams. However, I haven't found a good link as in how to use them easily. Moreover, is this the only way out or is there anyother method available that can help me in writing output in a JSON format.
Upvotes: 0
Views: 671
Reputation: 5768
As @Jason says, you can use PclStorage. Otherwise you can use DependencyService and write your code in Platform specific projects. You can take a look to this repo
This is something for Android
[assembly: Xamarin.Forms.Dependency(typeof(FilesImplementation))]
namespace TestReadFile.Droid
{
public class FilesImplementation : IFiles
{
public FilesImplementation()
{
}
public string ReadTextFile(string path, string fileName)
{
//throw new NotImplementedException();
using (System.IO.StreamReader sr = new System.IO.StreamReader(System.IO.Path.Combine(path, fileName))){
string line = sr.ReadToEnd();
sr.Close();
return line;
}
}
private string creaFileName(string directory, string fileName) {
string path = RootDirectory();
string file = System.IO.Path.Combine(path, fileName);
return file;
}
public void WriteTextFile(string path, string fileName, string stringToWrite)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.Path.Combine(path, fileName),false))
{
sw.WriteLine(stringToWrite);
sw.Close();
}
}
public string RootDirectory()
{
File path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
return path.AbsolutePath;
}
}
}
And this is PCL interface
public interface IFiles
{
string ReadTextFile(string path, string fileName);
void WriteTextFile(string path, string filename, string stringToWrite);
string RootDirectory();
}
Upvotes: 1