Skip to content

Instantly share code, notes, and snippets.

@LanceMcCarthy
Last active March 23, 2020 00:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanceMcCarthy/693ab82aa498cadf75e9fe778c4242ad to your computer and use it in GitHub Desktop.
Save LanceMcCarthy/693ab82aa498cadf75e9fe778c4242ad to your computer and use it in GitHub Desktop.
XamarinForms NET Standard 2.0
public static class FileExtensions
{
private static readonly string LocalFolder;
static FileExtensions()
{
// Gets the target platform's valid save location
LocalFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
}
// Byte[] extension methods
public static async Task<string> SaveToLocalFolderAsync(this byte[] dataBytes, string fileName)
{
return await Task.Run(() =>
{
// Use Combine so that the correct file path slashes are used
var filePath = Path.Combine(LocalFolder, fileName);
if (File.Exists(filePath))
File.Delete(filePath);
File.WriteAllBytes(filePath, dataBytes);
return filePath;
});
}
public static async Task<byte[]> LoadFileBytesAsync(string filePath)
{
return await Task.Run(() => File.ReadAllBytes(filePath));
}
// Stream extension methods
public static async Task<string> SaveToLocalFolderAsync(this Stream dataStream, string fileName)
{
// Use Combine so that the correct file path slashes are used
var filePath = Path.Combine(LocalFolder, fileName);
if (File.Exists(filePath))
File.Delete(filePath);
using (var fileStream = File.OpenWrite(filePath))
{
if (dataStream.CanSeek)
dataStream.Position = 0;
await dataStream.CopyToAsync(fileStream);
return filePath;
}
}
public static async Task<Stream> LoadFileStreamAsync(string filePath)
{
return await Task.Run(() =>
{
using (var fileStream = File.OpenRead(filePath))
{
return fileStream;
}
});
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Telerik.XamarinForms.DataControls"
xmlns:viewModels="clr-namespace:NetStandardTest.UpdatedPortable.ViewModels;assembly=NetStandardTest.UpdatedPortable"
x:Class="NetStandardTest.Forms.StartPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image x:Name="BackgroundImage"
Grid.RowSpan="2"/>
<Frame BackgroundColor="White"
HorizontalOptions="Center"
VerticalOptions="Center"
Margin="20">
<Label x:Name="OutputLabel"
LineBreakMode="CharacterWrap"/>
</Frame>
<Button Text="Save File"
Clicked="Button_OnClicked"
Margin="20"
Grid.Row="1" />
</Grid>
</ContentPage>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StartPage : ContentPage
{
private readonly HttpClient client;
private string imageFileName = "downloadedImage.jpg";
public StartPage()
{
InitializeComponent();
client = new HttpClient();
}
private async void Button_OnClicked(object sender, EventArgs e)
{
await DownloadAndSaveImage();
}
private async Task DownloadAndSaveImage()
{
try
{
using (var response = await client.GetStreamAsync("https://picsum.photos/200/300/?random&blur"))
{
var filePath = await response.SaveToLocalFolderAsync(imageFileName);
// Using FileImageSource just to confirm the image was saved as a file
BackgroundImage.Source = new FileImageSource { File = filePath };
OutputLabel.Text = $"Image file saved to\r\n\n{filePath}";
}
}
catch (Exception ex)
{
Debug.WriteLine($"DownloadAndSaveImage Exception: {ex}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment