Created
December 10, 2014 11:01
-
-
Save aliozgur/28769a2afefa37bf69c8 to your computer and use it in GitHub Desktop.
Xamarin.Forms : File service to save/load your objects as Json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Xml; | |
using System.Xml.Serialization; | |
using MonoTouch.UIKit; | |
using System.Collections; | |
using System.Collections.Generic; | |
using MonoTouch.Foundation; | |
/// <summary> | |
/// This class contains the code shown in the Xamarin article "Working with the File System" | |
/// </summary> | |
public class FileSystem | |
{ | |
public static string DocumentsPath | |
{ | |
get | |
{ | |
string value = UIDevice.CurrentDevice.SystemVersion.Split('.')[0]; | |
int systemVersion = -1; | |
Int32.TryParse(value, out systemVersion); | |
string folder = string.Empty; | |
if (systemVersion > 7) | |
{ | |
folder = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0]; | |
} | |
else | |
{ | |
folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); | |
} | |
return folder; | |
} | |
} | |
public static string LibraryPath | |
{ | |
get | |
{ | |
FileSystem.CreateDirIfNotExists("Library"); | |
return Path.Combine(FileSystem.DocumentsPath, "Library"); | |
} | |
} | |
public static string TmpPath | |
{ | |
get | |
{ | |
FileSystem.CreateDirIfNotExists("tmp"); | |
return Path.Combine(FileSystem.DocumentsPath, "tmp"); | |
} | |
} | |
public static int SysMajorVersion | |
{ | |
get | |
{ | |
string value = UIDevice.CurrentDevice.SystemVersion.Split('.')[0]; | |
int result = -1; | |
Int32.TryParse(value, out result); | |
return result; | |
} | |
} | |
public static void CreateDirIfNotExists(string name) | |
{ | |
var dir = FileSystem.ReadDirectories(FileSystem.DocumentsPath); | |
if (!dir.Exists(x => x.Equals(name))) | |
{ | |
try | |
{ | |
FileSystem.CreateDirectory(name); | |
} | |
catch (Exception) | |
{ | |
} | |
} | |
} | |
public static string ReadText(string path) | |
{ | |
var text = string.Empty; | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
// Sample code from the article | |
text = System.IO.File.ReadAllText(path); | |
// Output to app UITextView | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
if (FileSystem.FileExists(path)) | |
{ | |
NSString str = NSString.FromData(NSData.FromFile(path), NSStringEncoding.UTF8); | |
text = str != null ? str.ToString() : string.Empty; | |
} | |
} | |
return text; | |
} | |
public static List<string> ReadDirectories(string path) | |
{ | |
var list = new List<string>(); | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
// Sample code from the article | |
var directories = Directory.EnumerateDirectories(path); | |
foreach (var item in directories) | |
{ | |
var folder = item.Replace(item, string.Empty); | |
var itemPath = item; | |
if (string.IsNullOrWhiteSpace(folder)) | |
itemPath = Path.Combine(path, item); | |
list.Add(itemPath); | |
} | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
NSError err; | |
var contents = fileManager.GetDirectoryContent(path, out err); | |
if (contents != null) | |
{ | |
foreach (var item in contents) | |
{ | |
if (!fileManager.FileExists(item)) | |
list.Add(Path.Combine(path, item)); | |
} | |
} | |
} | |
return list; | |
} | |
public static List<string> ReadDirOrFiles(string path) | |
{ | |
var list = new List<string>(); | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
var filename = fileManager.DisplayName(path); | |
var nsstr = new NSString(filename); | |
if (!string.IsNullOrWhiteSpace(nsstr.PathExtension)) | |
path = path.Replace(filename, ""); | |
var fileOrDirectory = Directory.EnumerateFileSystemEntries(path); | |
foreach (var item in fileOrDirectory) | |
{ | |
var folder = item.Replace(item, string.Empty); | |
var itemPath = item; | |
if (string.IsNullOrWhiteSpace(folder)) | |
itemPath = Path.Combine(path, item); | |
list.Add(itemPath); | |
} | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
var filename = fileManager.DisplayName(path); | |
var nsstr = new NSString(filename); | |
NSError err; | |
if (!string.IsNullOrWhiteSpace(nsstr.PathExtension)) | |
path = path.Replace(filename, ""); | |
var contents = fileManager.GetDirectoryContent(path, out err); | |
if (contents != null) | |
{ | |
foreach (var item in contents) | |
{ | |
list.Add(Path.Combine(path, item)); | |
} | |
} | |
} | |
return list; | |
} | |
public static void WriteFile(string path, string text) | |
{ | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
// Sample code from the article | |
File.WriteAllText(path, text); | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
var data = NSData.FromString(text); | |
fileManager.CreateFile(path, data, new NSFileAttributes()); | |
} | |
} | |
public static void CreateDirectory(string name) | |
{ | |
// Sample code from the article | |
var directoryname = Path.Combine(FileSystem.DocumentsPath, name); | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
Directory.CreateDirectory(directoryname); | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
NSError error; | |
bool refer = true; | |
var folderExists = fileManager.FileExists(directoryname, ref refer); | |
if (!folderExists) | |
{ | |
fileManager.CreateDirectory(directoryname, false, new NSFileAttributes(), out error); | |
} | |
} | |
} | |
public static bool FileExists(string path) | |
{ | |
bool success = false; | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
success = File.Exists(path); | |
} | |
else | |
{ | |
success = NSFileManager.DefaultManager.FileExists(path); | |
} | |
return success; | |
} | |
public static bool DirectoryExists(string path) | |
{ | |
bool success = false; | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
success = Directory.Exists(path); | |
} | |
else | |
{ | |
bool refer = false; | |
success = NSFileManager.DefaultManager.FileExists(path, ref refer); | |
} | |
return success; | |
} | |
public static FileItem GetInfo(string path) | |
{ | |
var file = new FileItem(); | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
DirectoryInfo dirInfo = new DirectoryInfo(path); | |
if (dirInfo != null) | |
{ | |
file.id = dirInfo.Name; | |
file.itemName = dirInfo.Name; | |
file.itemPath = dirInfo.FullName; | |
file.isDir = true; | |
} | |
else if (dirInfo == null) | |
{ | |
FileInfo finfo = new FileInfo(path); | |
file.id = finfo.Name; | |
file.itemName = finfo.Name; | |
file.itemPath = finfo.FullName; | |
file.isDir = false; | |
file.fileSizeB = finfo.Length; | |
file.dateCreated = finfo.CreationTime; | |
file.extension = finfo.Extension; | |
} | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
var nsStr = new NSString(path); | |
var ext = nsStr.PathExtension; | |
var isFile = !string.IsNullOrWhiteSpace(ext); | |
var name = fileManager.DisplayName(path); | |
var attr = fileManager.GetAttributes(path); | |
file.id = name; | |
file.itemName = name; | |
file.itemPath = path; | |
file.isDir = !isFile; | |
if (isFile) | |
{ | |
DateTime date = DateTime.Now; | |
DateTime.TryParse(attr.CreationDate.ToString(), out date); | |
file.fileSizeB = attr.FileSize.Value; | |
file.dateCreated = date; | |
file.extension = ext; | |
} | |
} | |
return file; | |
} | |
public static bool DeleteFile(string path) | |
{ | |
bool success = false; | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
if (File.Exists(path)) | |
{ | |
try | |
{ | |
File.Delete(path); | |
success = true; | |
} | |
catch | |
{ | |
success = false; | |
} | |
} | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
NSError error; | |
var fileExists = fileManager.FileExists(path); | |
if (fileExists) | |
success = fileManager.Remove(path, out error); | |
} | |
return success; | |
} | |
public static bool DeleteFolder(string path) | |
{ | |
bool success = false; | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
if (Directory.Exists(path)) | |
{ | |
try | |
{ | |
Directory.Delete(path); | |
success = true; | |
} | |
catch | |
{ | |
success = false; | |
} | |
} | |
} | |
else | |
{ | |
var fileManager = NSFileManager.DefaultManager; | |
NSError error; | |
bool refer = true; | |
var folderExists = fileManager.FileExists(path, ref refer); | |
if (folderExists) | |
success = fileManager.Remove(path, out error); | |
} | |
return success; | |
} | |
public static void CopyItem(string src, string dest, bool overwrite) | |
{ | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
File.Copy(src, dest, overwrite); | |
} | |
else | |
{ | |
var filemanager = NSFileManager.DefaultManager; | |
var fileName = filemanager.DisplayName(src); | |
dest = Path.Combine(dest, fileName); | |
if (filemanager.FileExists(dest) && overwrite) | |
{ | |
NSError err; | |
filemanager.Remove(dest, out err); | |
filemanager.Copy(src, dest, out err); | |
} | |
else if (!filemanager.FileExists(dest)) | |
{ | |
NSError err; | |
filemanager.Copy(src, dest, out err); | |
} | |
} | |
} | |
public static void MoveItem(string src, string dest, bool overwrite) | |
{ | |
if (FileSystem.SysMajorVersion <= 7) | |
{ | |
File.Move(src, dest); | |
} | |
else | |
{ | |
var filemanager = NSFileManager.DefaultManager; | |
var fileName = filemanager.DisplayName(src); | |
dest = Path.Combine(dest, fileName); | |
if (filemanager.FileExists(dest) && overwrite) | |
{ | |
NSError err; | |
filemanager.Remove(dest, out err); | |
filemanager.Move(src, dest, out err); | |
} | |
else if (!filemanager.FileExists(dest)) | |
{ | |
NSError err; | |
filemanager.Move(src, dest, out err); | |
} | |
} | |
} | |
} | |
public class FileItem | |
{ | |
public string id; | |
public string itemName; | |
public string itemPath; | |
public bool isHeader; | |
public bool isDir; | |
public float fileSizeB; | |
public float fileSizeKB | |
{ | |
get { return fileSizeB / 1024.0f; } | |
} | |
public float fileSizeMB | |
{ | |
get { return fileSizeKB / 1024.0f; } | |
} | |
public DateTime dateCreated; | |
public string extension; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace MyNamespace | |
{ | |
public interface IJsonFileService | |
{ | |
T LoadFromLibrary<T>(string fileName); | |
bool SaveToLibrary<T>( T instance, string fileName); | |
bool DeleteFromLibrary(string fileName); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using Xamarin.Forms; | |
using MyNamespace.Android; | |
using Newtonsoft.Json; | |
[assembly: Dependency(typeof(JsonFileService))] | |
namespace MyNamespace.Android | |
{ | |
public class JsonFileService:IJsonFileService | |
{ | |
public JsonFileService() | |
{ | |
} | |
private string PreparePath(string fileName) | |
{ | |
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); | |
var path = Path.Combine(documentsPath, fileName); | |
return path; | |
} | |
public T LoadFromLibrary<T>(string fileName) | |
{ | |
var path = PreparePath(fileName); | |
if (!File.Exists(path)) | |
return default(T); | |
using (FileStream fs = File.Open(path, FileMode.Open)) | |
{ | |
using (StreamReader sr = new StreamReader(fs)) | |
{ | |
using (JsonTextReader jr = new JsonTextReader(sr)) | |
{ | |
JsonSerializer serializer = new JsonSerializer(); | |
return serializer.Deserialize<T>(jr); | |
} | |
} | |
} | |
} | |
public bool SaveToLibrary<T>(T instance, string fileName) | |
{ | |
var path = PreparePath(fileName); | |
using (FileStream fs = File.Open(path, FileMode.Create)) | |
{ | |
using (StreamWriter sw = new StreamWriter(fs)) | |
{ | |
using (JsonWriter jw = new JsonTextWriter(sw)) | |
{ | |
jw.Formatting = Formatting.Indented; | |
JsonSerializer serializer = new JsonSerializer(); | |
serializer.Serialize(jw, instance); | |
return true; | |
} | |
} | |
} | |
} | |
public bool DeleteFromLibrary(string fileName) | |
{ | |
var path = PreparePath(fileName); | |
if (!File.Exists(path)) | |
return false; | |
File.Delete(path); | |
return true; | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MyNamespace.iOS; | |
using System.IO; | |
using Newtonsoft.Json; | |
using Xamarin.Forms; | |
[assembly: Dependency(typeof (JsonFileService))] | |
namespace MyNamespace.iOS | |
{ | |
public class JsonFileService:IJsonFileService | |
{ | |
public JsonFileService () | |
{ | |
} | |
private string PreparePath (string fileName) | |
{ | |
// Documents folder | |
string libraryPath = FileSystem.LibraryPath; | |
// Library folder | |
var path = Path.Combine (libraryPath, fileName); | |
return path; | |
} | |
public T LoadFromLibrary<T>(string fileName) | |
{ | |
var path = PreparePath (fileName); | |
if (!FileSystem.FileExists (path)) | |
return default(T); | |
using (FileStream fs = File.Open (path, FileMode.Open)) { | |
using (StreamReader sr = new StreamReader (fs)) { | |
using (JsonTextReader jr = new JsonTextReader (sr)) { | |
JsonSerializer serializer = new JsonSerializer (); | |
return serializer.Deserialize<T>(jr); | |
} | |
} | |
} | |
} | |
public bool SaveToLibrary<T>( T instance, string fileName) | |
{ | |
var path = PreparePath (fileName); | |
using (FileStream fs = File.Open (path, FileMode.Create)) { | |
using (StreamWriter sw = new StreamWriter (fs)) { | |
using (JsonWriter jw = new JsonTextWriter (sw)) { | |
jw.Formatting = Formatting.Indented; | |
JsonSerializer serializer = new JsonSerializer (); | |
serializer.Serialize (jw, instance); | |
return true; | |
} | |
} | |
} | |
} | |
public bool DeleteFromLibrary(string fileName) | |
{ | |
var path = PreparePath(fileName); | |
return FileSystem.DeleteFile (path); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MyNamespace | |
{ | |
public class LogonService | |
{ | |
private IJsonFileService _fileSvc; | |
public const string TokenFileName = "token.json"; | |
public LogonService() | |
{ | |
_fileSvc = DependencyService.Get<IJsonFileService>(); | |
} | |
public void Logout() | |
{ | |
//TODO: Logout logic if needed | |
_fileSvc.DeleteFromLibrary(TokenFileName); | |
} | |
public void Logon() | |
{ | |
Token token = null; | |
//TODO: var token = ApiClient.Get(); | |
_fileSvc.SaveToLibrary<Token>(token, TokenFileName); | |
} | |
public Token ReadToken() | |
{ | |
var token = _fileSvc.LoadFromLibrary<Token>(TokenFileName); | |
return token; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment