DownloadAsync result file is null - c#

I use Live SDK 5.6 and I'm trying to download file from OneDrive. Using CreateBackgroundDownloadAsync (innerItem.ID + "/Content"), why is result file null?
foreach (var innerItem in resultItems.data)
{
if (innerItem.name == "MoneyNote.db")
{
LiveDownloadOperation operation = await liveConnectClient.CreateBackgroundDownloadAsync(innerItem.id + "/Content");
//LiveDownloadOperationResult downloadResult = await operation.StartAsync();
var downloadResult = await operation.StartAsync();
if (downloadResult.File != null)
{
StorageFile downFile = await ApplicationData.Current.LocalFolder.GetFileAsync("MoneyNote.db");
await downloadResult.File.MoveAndReplaceAsync(downFile);
messagePrint(true);
}
else
{
messagePrint(false);
}
}
}

I think the problem may be, because you are creating background download (not downloading in the background), then you start this download operation, but file needs time to be downloaded. In this case probably easier would be just to download a file like this:
foreach (var innerItem in resultItems.data)
{
if (innerItem.name == "MoneyNote.db")
{
StorageFile downFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MoneyNote.db", CreationCollisionOption.ReplaceExisting);
var result = await liveConnectClient.BackgroundDownloadAsync(innerItem.id + "/content", downFile);
messagePrint(true);
}
}

Related

Xamarin Unauthorized Access Permission In downloading a file

I've been trying to create a function where the user will download a file(PDF) when a button is clicked.
I stored the file in firebase storage and can be accessible via url/link. I found this solution How to download files in Xamarin.Forms? that helps you download from a url. However I got an error that say **System.UnauthorizedAccessException:** 'Access to the path '/data/user/0/com.companyname.pawadopt_v5/files' is denied.' I already made sure to check and request permission using Xamarin.Essentials but I keep getting this error even with Permission.Granted for StorageRead and StorageWrite.
Here is my code:
Download Function
public async Task<bool> DownloadFile(string fileURL)
{
var checkPermission = await PermissionServices.PermissionClientInstance.checkStorage();
if(checkPermission == true)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
try
{
var client = new HttpClient();
var downloadStream = await client.GetStreamAsync(fileURL);
var fileStream = File.Create(path);
await downloadStream.CopyToAsync(fileStream);
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
return false;
}
}
Check and Request Permission
var Readpermission = await Permissions.CheckStatusAsync<Permissions.StorageRead>();
var Writepermission = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();
if (Readpermission != PermissionStatus.Granted || Writepermission != PermissionStatus.Granted)
{
Readpermission = await Permissions.RequestAsync<Permissions.StorageRead>();
Writepermission = await Permissions.RequestAsync<Permissions.StorageWrite>();
}
if (Readpermission != PermissionStatus.Granted && Writepermission != PermissionStatus.Granted)
return false;
else
return true;
What are your thoughts and solutions about this?
Any ideas and solution are greatly appreciated
UPDATE
When I changed the path into string localPath = Path.Combine(FileSystem.AppDataDirectory,"File.pdf");, No error shows and prompt the 'Download Successful'. However I cant find where this local path is.

Having issue with with Progress Dialog using Acr.UserDialogs in xamarin forms iOS App

I am having a problem with showing progress bar using nuget package (Acr.UserDialog) in xamarin forms iOS. with the same code snippet, its working well in Android platform.
using (UserDialogs.Instance.Loading("Loading", null, null, true, MaskType.Black)) {
await Task.Run(() => {
// Code Logic Goes here ...
});
}
A version of ACR UserDialogs Library:
PCL Project - v6.5.1
iOS Project - v7.0.0
if anyone knows the solution for this issue, please provide a solution.
https://forums.xamarin.com/discussion/67832/implementing-file-picker-example-into-a-cross-platform-application
Please check this:
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
var fileFullName = file.FilePath.Substring(file.FilePath.LastIndexOf('\\') + 1);
var extension = Path.GetExtension(file.FileName).Substring(1);
var fileName = Path.GetFileNameWithoutExtension("Pick_" + extension + "_File_" + DateTime.UtcNow.ToString("MMddyyyy_hhmmss"));
using (Stream stream = file.GetStream())
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
filePath = ms.ToArray().SaveAttachmentInLocalFolder(fileName, extension);
}
}
public async Task GetPdfDataAsync(byte[] fileBytes)
{
try
{
var localPath = string.Empty;
var fileName = Guid.NewGuid().ToString();
localPath =
Task.Run(() => _localFileProvider.SaveFileToDisk(fileBytes, $"{fileName}.pdf")).Result;
if (string.IsNullOrWhiteSpace(localPath))
{
await PageDialogService.DisplayAlertAsync("Error loading PDF", "Computer says no", "OK");
return;
}
if (Device.RuntimePlatform == Device.Android)
Pdfviewsource = $"file:///android_asset/pdfjs/pdfjs/web/viewer.html?file={WebUtility.UrlEncode(localPath)}";
else
{
Pdfviewsource = localPath;
}
}
catch (Exception) { }
}

How to save image from clipboard to file in UWP

Is there any equivalent of
Clipboard.GetImage().Save(FileName, Imaging.ImageFormat.Jpeg)
for UWP (Windows Universal Platform)?
I.e. saving the graphics image from clipboard into jpg format to file.
I am looking for example in vb.net/C#.
I have already started with
Dim datapackage = DataTransfer.Clipboard.GetContent()
If datapackage.Contains(StandardDataFormats.Bitmap) Then
Dim r As Windows.Storage.Streams.RandomAccessStreamReference = Await datapackage.GetBitmapAsync()
...
but I do not know how to continue (and even if I have even started correctly).
The first step is to try and get the image from the clipboard, if it exists:
var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
IRandomAccessStreamReference imageReceived = null;
try
{
imageReceived = await dataPackageView.GetBitmapAsync();
}
catch (Exception ex)
{
}
If it exists, launch a file save picker, choose where to save the image, and copy the image stream to the new file.
if (imageReceived != null)
{
using (var imageStream = await imageReceived.OpenReadAsync())
{
var fileSave = new FileSavePicker();
fileSave.FileTypeChoices.Add("Image", new string[] { ".jpg" });
var storageFile = await fileSave.PickSaveFileAsync();
using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await imageStream.AsStreamForRead().CopyToAsync(stream.AsStreamForWrite());
}
}
}
}

How to relate between open file picker and storage file?

look for this error and tell me your opinion to solve this problem
I was making window phone Application :
its can't save my picked file in a storage file to trim it as media
or I can not relate between open file picker and storage file if anyone have any ideas how to relate between them or have any demos please tell me
I'm not sure I understood your problem. Here is my code for picking a file and write into it in WinRT/Win10 store app.
private async void SaveFileExecute()
{
var fileNameTab = FileName.Split('.');
var extension = fileNameTab[1];
var fileName = fileNameTab[0];
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
SuggestedFileName = fileName
};
savePicker.FileTypeChoices.Add(extension, new List<string> { "." + extension });
var saveFile = await savePicker.PickSaveFileAsync();
if (saveFile != null)
{
using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outputStream = fileStream.GetOutputStreamAt(0))
{
using (var dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteBytes(SelectedFile.Data);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
}

how to empty a directory in c# xaml metro style?

i have this c# code and i want to delete a certain sub directory in Documents Library. However this produces an error because the directory is not empty. I hope someone can guide me on how to do this.
thank you for any prompt reply.
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
var queryResult = storageFolder.CreateFolderQuery();
IReadOnlyList<StorageFolder> folderList = await queryResult.GetFoldersAsync();
foreach (StorageFolder folder in folderList)
{
await folder.DeleteAsync();
}
You could use the StorageFolder.GetFilesAsync() to obtain a list of all the files present in the folders and delete them prior to deleting the folders since there is no way in the DeleteAsync() method to specify subfolders and files.
More info: StorageFolder class | MSDN
Hope this may help.
public async void deletefile()
{
StorageFolder sourceFolder = ApplicationData.Current.TemporaryFolder;
// sourceFolder = await sourceFolder.GetFolderAsync("Test");
// await sourceFolder.DeleteAsync(StorageDeleteOption.PermanentDelete);
// var files = await sourceFolder.GetFilesAsync();
IReadOnlyList<StorageFile> folderList = await sourceFolder.GetFilesAsync();
if (folderList.Count > 0)
{
foreach (StorageFile f1 in folderList)
{
await f1.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
//StorageFile retfile = await ApplicationData.Current.TemporaryFolder.GetFileAsync("MysoundFile.mp3");
// if (retfile != null)
// {
// await retfile.DeleteAsync(StorageDeleteOption.PermanentDelete);
// }
}

Categories