Skip to content

Instantly share code, notes, and snippets.

@julesx
Last active October 4, 2018 07:43
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julesx/496066ffc006141de3fce3d2f0de3fba to your computer and use it in GitHub Desktop.
Save julesx/496066ffc006141de3fce3d2f0de3fba to your computer and use it in GitHub Desktop.
Xamarin Forms file opener
using Android.Content;
using Mobile.Core.Droid.NativeImplementations;
using Mobile.Core.Interfaces;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(DocumentViewer))]
namespace Mobile.Core.Droid.NativeImplementations
{
public class DocumentViewer : IDocumentViewer
{
public void ShowDocumentFile(string filepath, string mimeType)
{
var uri = global::Android.Net.Uri.Parse("file://" + filepath);
var intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, mimeType);
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
Forms.Context.StartActivity(intent);
}
public DocumentViewer()
{
}
}
}
using System.IO;
using Mobile.Core.Interfaces;
namespace Mobile.Core.Droid.NativeImplementations
{
public class AndroidExternalStorageWriter : IAndroidExternalStorageWriter
{
public string CreateFile(string filename, byte[] bytes)
{
if (!Directory.Exists(Path.Combine(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "YourAppName")))
Directory.CreateDirectory(Path.Combine(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "YourAppName"));
var path = Path.Combine(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "YourAppName", filename);
File.WriteAllBytes(path, bytes);
return path;
}
public bool FileExists(string filename)
{
var path = ConstructFilePath(filename);
return File.Exists(path);
}
public void DeleteFile(string filename)
{
var path = ConstructFilePath(filename);
File.Delete(path);
}
public string ConstructFilePath(string filename)
{
return Path.Combine(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "YourAppName", filename);
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mobile.Core.Interfaces;
using PCLStorage;
using Xamarin.Forms;
namespace Mobile.Core
{
public static class FileManager
{
private static string ConstructFilePath(string filename)
{
switch (Device.RuntimePlatform)
{
case Device.Android:
var androidWriter = DependencyService.Get<IAndroidExternalStorageWriter>();
return androidWriter.ConstructFilePath(filename);
case Device.iOS:
var rootFolder = FileSystem.Current.LocalStorage;
return Path.Combine(rootFolder.Path, filename);
default:
return null;
}
}
public async static Task<bool> FileExists(string filename)
{
switch (Device.RuntimePlatform)
{
case Device.Android:
var androidWriter = DependencyService.Get<IAndroidExternalStorageWriter>();
return androidWriter.FileExists(filename);
case Device.iOS:
var filepath = ConstructFilePath(filename);
var result = await FileSystem.Current.LocalStorage.CheckExistsAsync(filepath);
return result == ExistenceCheckResult.FileExists;
default:
return false;
}
}
public async static void DeleteFile(string filename)
{
try
{
switch (Device.RuntimePlatform)
{
case Device.Android:
var androidWriter = DependencyService.Get<IAndroidExternalStorageWriter>();
androidWriter.DeleteFile(filename);
break;
case Device.iOS:
var filepath = ConstructFilePath(filename);
var file = await FileSystem.Current.LocalStorage.GetFileAsync(filepath);
await file.DeleteAsync();
break;
}
}
catch (Exception)
{
}
}
public static Exception OpenFile(string filename)
{
try
{
var documentViewer = DependencyService.Get<IDocumentViewer>();
var mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
if (Path.GetExtension(filename).ToLower() == ".pdf")
mimeType = "application/pdf";
else if (Path.GetExtension(filename).ToLower() == ".doc")
mimeType = "application/msword";
else if (Path.GetExtension(filename).ToLower() == ".xls")
mimeType = "application/vnd.ms-excel";
else if (Path.GetExtension(filename).ToLower() == ".xlsx")
mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
else if (Path.GetExtension(filename).ToLower() == ".ppt")
mimeType = "application/vnd.ms-powerpoint";
else if (Path.GetExtension(filename).ToLower() == ".jpg")
mimeType = "image/jpeg";
var filepath = ConstructFilePath(filename);
documentViewer.ShowDocumentFile(filepath, mimeType);
}
catch (Exception ex)
{
return ex;
}
return null;
}
public static async Task<string> SaveFile(byte[] fileBytes, string filename)
{
try
{
string filepath = null;
if (Device.RuntimePlatform == Device.Android)
{
var androidWriter = DependencyService.Get<IAndroidExternalStorageWriter>();
filepath = androidWriter.CreateFile(filename, fileBytes.ToArray());
}
else if (Device.RuntimePlatform == Device.iOS)
{
var rootFolder = FileSystem.Current.LocalStorage;
using (var pdfBytes = new MemoryStream(fileBytes))
{
var file = await rootFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
filepath = file.Path;
var newFile = await file.OpenAsync(FileAccess.ReadAndWrite);
using (var outputStream = newFile)
pdfBytes.CopyTo(outputStream);
}
}
if (string.IsNullOrEmpty(filepath))
return "Error: Unable to save file";
}
catch (Exception ex)
{
return "Error: " + ex.Message;
}
return "";
}
}
}
namespace Mobile.Core.Interfaces
{
public interface IAndroidExternalStorageWriter
{
string CreateFile(string filename, byte[] bytes);
bool FileExists(string filename);
string ConstructFilePath(string filename);
void DeleteFile(string filename);
}
}
using System;
using System.IO;
using Foundation;
using Mobile.Core.iOS.NativeImplementations;
using Mobile.Core.Interfaces;
using QuickLook;
using UIKit;
[assembly: Xamarin.Forms.Dependency(typeof(DocumentViewer))]
namespace Mobile.Core.iOS.NativeImplementations
{
public class DocumentViewer : IDocumentViewer
{
public DocumentViewer()
{
}
public void ShowDocumentFile(string filepath, string mimeType)
{
var fileinfo = new FileInfo(filepath);
var previewController = new QLPreviewController
{
DataSource = new PreviewControllerDataSource(fileinfo.FullName, fileinfo.Name)
};
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
while (vc.PresentedViewController != null)
{
vc = vc.PresentedViewController;
}
vc?.PresentViewController(previewController, true, null);
}
}
public class DocumentItem : QLPreviewItem
{
private readonly string _uri;
public DocumentItem(string title, string uri)
{
ItemTitle = title;
_uri = uri;
}
public override string ItemTitle { get; }
public override NSUrl ItemUrl => NSUrl.FromFilename(_uri);
}
public class PreviewControllerDataSource : QLPreviewControllerDataSource
{
private readonly string _url;
private readonly string _filename;
public PreviewControllerDataSource(string url, string filename)
{
_url = url;
_filename = filename;
}
public override IQLPreviewItem GetPreviewItem(QLPreviewController controller, nint index)
{
return new DocumentItem(_filename, _url);
}
public override nint PreviewItemCount(QLPreviewController controller)
{
return 1;
}
}
}
@Shoaib540
Copy link

its very useful ..i just want to dicuss one thing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment