void CopyFileToDocumentsDirectory(NSUrl fromUrl) { NSUrl toURL = DocumentsDirectory.Append(fromUrl.LastPathComponent, false); bool success = false; NSError error; NSFileCoordinator fileCoordinator = new NSFileCoordinator(); fileCoordinator.CoordinateWriteWrite(fromUrl, NSFileCoordinatorWritingOptions.ForMoving, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out error, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out error); if (success) { var attributes = new NSFileAttributes { FileExtensionHidden = true }; fileManager.SetAttributes(attributes, dst.Path); Console.WriteLine("Moved file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) { Console.WriteLine("Couldn't move file: {0} to: {1}. Error: {3}.", fromUrl.AbsoluteString, toURL.AbsoluteString, error.Description); } }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("Finished"); Console.WriteLine("File downloaded in : {0}", location); NSFileManager fileManager = NSFileManager.DefaultManager; var URLs = fileManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); NSUrl documentsDictionry = URLs[0]; NSUrl originalURL = downloadTask.OriginalRequest.Url; NSUrl destinationURL = documentsDictionry.Append(controller.FileName, false); NSError removeCopy; NSError errorCopy; fileManager.Remove(destinationURL, out removeCopy); bool success = fileManager.Copy(location, destinationURL, out errorCopy); if (success) { controller.Dismiss(); } else { Console.WriteLine("Error during the copy: {0}", errorCopy.LocalizedDescription); } }
public static Task<NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl) { var tcs = new TaskCompletionSource<NSUrl>(); NSUrl localDocDir = GetDocumentDirectoryUrl (); NSUrl toURL = localDocDir.Append (fromUrl.LastPathComponent, false); bool success = false; NSError coordinationError, copyError = null; NSFileCoordinator fileCoordinator = new NSFileCoordinator (); ThreadPool.QueueUserWorkItem (_ => { fileCoordinator.CoordinateReadWrite (fromUrl, 0, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out coordinationError, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out copyError); if (success) { var attributes = new NSFileAttributes { ExtensionHidden = true }; fileManager.SetAttributes (attributes, dst.Path); Console.WriteLine ("Copied file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) Console.WriteLine ("Couldn't copy file: {0} to: {1}. Error: {2}.", fromUrl.AbsoluteString, toURL.AbsoluteString, (coordinationError ?? copyError).Description); tcs.SetResult(toURL); }); return tcs.Task; }
void CopyFileToDocumentsDirectory(NSUrl fromUrl) { NSUrl toURL = DocumentsDirectory.Append (fromUrl.LastPathComponent, false); bool success = false; NSError error; NSFileCoordinator fileCoordinator = new NSFileCoordinator (); fileCoordinator.CoordinateWriteWrite (fromUrl, NSFileCoordinatorWritingOptions.ForMoving, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out error, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out error); if (success) { var attributes = new NSFileAttributes { ExtensionHidden = true }; fileManager.SetAttributes (attributes, dst.Path); Console.WriteLine ("Moved file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) Console.WriteLine ("Couldn't move file: {0} to: {1}. Error: {3}.", fromUrl.AbsoluteString, toURL.AbsoluteString, error.Description); }
public NSUrl moveItemToDocumentsDirectory(string fileName, string fileExtension) { NSFileManager fileManager = NSFileManager.DefaultManager; string[] dataPath = new string[] { applicationDocumentsDirectory() + "/" + fileName + "." + fileExtension }; NSUrl fileURLPrivate = NSBundle.MainBundle.GetUrlForResource(fileName, fileExtension); if (fileManager.FileExists(fileURLPrivate.Path)) { //First run, if file is not copied then copy, else return the path if already copied if (fileManager.FileExists(dataPath[0]) == false) { fileManager.Copy(fileURLPrivate.Path, dataPath[0], out NSError error); if (error == null) { return(NSUrl.CreateFileUrl(dataPath)); } else { Console.WriteLine("AWXamarin Error occured while copying"); } } else { return(NSUrl.CreateFileUrl(dataPath)); } Console.WriteLine("AWXamarin fileURLPrivate doesnt exist"); return(null); } return(null); }
/// <summary> /// Gets called if the download has been completed. /// </summary> public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { // The download location will be a file location. var sourceFile = location.Path; // Construct a destination file name. var destFile = downloadTask.OriginalRequest.Url.AbsoluteString.Substring(downloadTask.OriginalRequest.Url.AbsoluteString.LastIndexOf("/") + 1); Console.WriteLine("DidFinishDownloading - Task: {0}, Source file: {1}", downloadTask.TaskIdentifier, sourceFile); // Copy over to documents folder. Note that we must use NSFileManager here! File.Copy() will not be able to access the source location. NSFileManager fileManager = NSFileManager.DefaultManager; // Create the filename var documentsFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); NSUrl destinationURL = NSUrl.FromFilename(Path.Combine(documentsFolderPath, destFile)); // Remove any existing file in our destination NSError error; fileManager.Remove(DownloadController.targetFilename, out error); bool success = fileManager.Copy(sourceFile, DownloadController.targetFilename, out error); if (!success) { Console.WriteLine("Error during the copy: {0}", error.LocalizedDescription); } this.InvokeOnMainThread(() => this.controller.LoadImage()); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("Finished"); Console.WriteLine("File downloaded in : {0}", location); NSFileManager fileManager = NSFileManager.DefaultManager; var URLs = fileManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); NSUrl documentsDictionry = URLs [0]; NSUrl originalURL = downloadTask.OriginalRequest.Url; NSUrl destinationURL = documentsDictionry.Append("image1.png", false); NSError removeCopy; NSError errorCopy; fileManager.Remove(destinationURL, out removeCopy); bool success = fileManager.Copy(location, destinationURL, out errorCopy); if (success) { // we do not need to be on the main/UI thread to load the UIImage UIImage image = UIImage.FromFile(destinationURL.Path); InvokeOnMainThread(() => { controller.ImageView.Image = image; controller.ImageView.Hidden = false; controller.ProgressView.Hidden = true; }); } else { Console.WriteLine("Error during the copy: {0}", errorCopy.LocalizedDescription); } }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { string urlString = System.Web.HttpUtility.UrlDecode(downloadTask.CurrentRequest.Url.ToString()); string fileType = urlString.Substring(urlString.Length - 3); int idx = urlString.LastIndexOf('/'); string fileName = urlString.Substring(idx + 1); AppDelegate.filesDownloaded.Add(NSObject.FromObject(fileName)); var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var destinationPath = Path.Combine(documents, fileName); if (File.Exists(location.Path)) { NSFileManager fileManager = NSFileManager.DefaultManager; NSError error; // Remove the same name file in destination path. fileManager.Remove(destinationPath, out error); // Copy the file from the tmp directory to your destination path. The tmp file will be removed when this delegate finishes. bool success = fileManager.Copy(location.Path, destinationPath, out error); if (!success) { Console.WriteLine("Error during the copy: {0}", error.LocalizedDescription); } } int count = 0; for (nuint i = 0; i < AppDelegate.filesDownloading.Count; i++) { for (nuint j = 0; j < AppDelegate.filesDownloaded.Count; j++) { if (AppDelegate.filesDownloading.GetItem <NSObject>(i).Equals(AppDelegate.filesDownloading.GetItem <NSObject>(j))) { count = count + 1; } } } NSDictionary countDict = new NSDictionary("count", count); NSNotificationCenter.DefaultCenter.PostNotificationName("DownloadCount", this, countDict); if (count == (int)AppDelegate.filesDownloading.Count) { InvokeOnMainThread(delegate { var notification = new UILocalNotification(); notification.FireDate = NSDate.FromTimeIntervalSinceNow(1); notification.AlertAction = "McDonalds:File Download Complete"; notification.AlertBody = "McDonalds:File Download Complete"; notification.ApplicationIconBadgeNumber = 1; notification.SoundName = UILocalNotification.DefaultSoundName; UIApplication.SharedApplication.ScheduleLocalNotification(notification); UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; }); } }
private void LoadAudioFileList() { var soundDirectory = "/System/Library/Audio/UISounds"; var specificDesiredNames = new List <string> { "Bloom.caf", "Calypso.caf", "Choo_Choo.caf", "Fanfare.caf", "Ladder.caf", "Noir.caf", "Sherwood_Forest.caf", "Telegraph.caf", "Tiptoes.caf" }; var soundFiles = new List <string>(); using (var fileManager = new NSFileManager()) { var enumerator = fileManager.GetEnumerator(soundDirectory); while (true) { var item = enumerator.NextObject(); if (item == null) { break; } var itemName = item.ToString(); if ((itemName.Contains("sms") && !itemName.Contains("received")) || specificDesiredNames.Any(n => itemName.Contains(n))) { soundFiles.Add(itemName); } } NSError error; var destPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); foreach (var fileNameAndPath in soundFiles) { var src = $"{soundDirectory}/{fileNameAndPath}"; var fileName = fileNameAndPath; if (fileNameAndPath.Contains('/')) { fileName = fileNameAndPath.Split('/').Last(); } var dst = $"{destPath}/{fileName}"; fileManager.Copy(src, dst, out error); if (error != null) { Console.WriteLine(error.Description); } } } Console.WriteLine("***************** DONE *******************"); Console.WriteLine("***************** DONE *******************"); Console.WriteLine("***************** DONE *******************"); Console.WriteLine("***************** DONE *******************"); Console.WriteLine("***************** DONE *******************"); Console.WriteLine("***************** DONE *******************"); Console.WriteLine("***************** DONE *******************"); Console.WriteLine("***************** DONE *******************"); }
public async void Completed(NSUrlSessionTask downloadTask, NSUrl location) { NSFileManager fileManager = NSFileManager.DefaultManager; NSError errorCopy = null; var file = Load(downloadTask); LogManager.Shared.Log("Download Complete", file); file.IsCompleted = true; file.Status = BackgroundDownloadFile.FileStatus.Temporary; file.Percent = 1; //if (!AutoProcess) //{ // var sharedFolder = fileManager.GetContainerUrl(SharedContainerIdentifier); // fileManager.CreateDirectory(sharedFolder, true, null, out errorCopy); // var fileName = Path.GetFileName(file.Destination); // var newTemp = Path.Combine(sharedFolder.RelativePath, fileName); // var success1 = fileManager.Copy(location, NSUrl.FromFilename(newTemp), out errorCopy); // Console.WriteLine("Success: {0} {1}", success1, errorCopy); // file.TempLocation = newTemp; // return; //} var originalURL = downloadTask.OriginalRequest.Url; var dest = Path.Combine(Locations.BaseDir, file.Destination); NSUrl destinationURL = NSUrl.FromFilename(dest); NSError removeCopy; fileManager.Remove(destinationURL, out removeCopy); LogManager.Shared.Log("Copying Downloaded File", value: "Destination", key: dest); var success = fileManager.Copy(location, destinationURL, out errorCopy); if (success) { file.Status = BackgroundDownloadFile.FileStatus.Completed; } else { LogManager.Shared.Log("Error copying file", key: "Error", value: errorCopy?.LocalizedDescription ?? ""); } Console.WriteLine("Success: {0} {1}", success, errorCopy); file.Status = BackgroundDownloadFile.FileStatus.Completed; file.Destination = dest; await ProcessFile(file); FileCompleted?.InvokeOnMainThread(downloadTask, new CompletedArgs { File = file }); LogManager.Shared.Log("Download Completed", key: "Data", value: downloadTask.TaskDescription); }
private void CopyDownloadedImage(NSUrl location) { NSFileManager fileManager = NSFileManager.DefaultManager; NSError error; if (fileManager.FileExists(targetFileName)) { fileManager.Remove(targetFileName, out error); } bool success = fileManager.Copy(location.Path, targetFileName, out error); if (!success) { Console.WriteLine("Error during the copy: {0}", error.LocalizedDescription); } }
/// <summary> /// Gets called if the download has been completed. /// </summary> public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { // The download location will be a file location. var sourceFile = location.Path; // Construct a destination file name. var destFile = downloadTask.OriginalRequest.Url.AbsoluteString.Substring(downloadTask.OriginalRequest.Url.AbsoluteString.LastIndexOf("/") + 1); Console.WriteLine("DidFinishDownloading - Task: {0}, Source file: {1}", downloadTask.TaskIdentifier, sourceFile); // Copy over to documents folder. Note that we must use NSFileManager here! File.Copy() will not be able to access the source location. NSFileManager fileManager = NSFileManager.DefaultManager; // Create the filename var documentsFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); NSUrl destinationURL = NSUrl.FromFilename(Path.Combine(documentsFolderPath, destFile)); // Update download info object. var downloadInfo = AppDelegate.GetDownloadInfoByTaskId(downloadTask.TaskIdentifier); // Remove any existing file in our destination NSError error; fileManager.Remove(destinationURL, out error); bool success = fileManager.Copy(sourceFile, destinationURL.Path, out error); if (success) { // Update download info object. this.UpdateDownloadInfo(downloadInfo, DownloadInfo.STATUS.Completed, destinationURL); } else { // Clean up. downloadInfo.Reset(true); this.UpdateDownloadInfo(downloadInfo, DownloadInfo.STATUS.Cancelled, null); Console.WriteLine("Error during the copy: {0}", error.LocalizedDescription); } this.InvokeOnMainThread(() => { this.controller.TableView.ReloadData(); }); // Serialize all info to disk. AppDelegate.SerializeAvailableDownloads(); }
/** * Move the downloaded file to it's destination */ public bool MoveDownloadedFile(DownloadFileImplementation file, NSUrl location, string destinationPathName) { NSFileManager fileManager = NSFileManager.DefaultManager; var destinationURL = new NSUrl(destinationPathName, false); NSError removeCopy; NSError errorCopy; fileManager.Remove(destinationURL, out removeCopy); var success = fileManager.Copy(location, destinationURL, out errorCopy); if (!success) { file.StatusDetails = errorCopy.LocalizedDescription; file.Status = DownloadFileStatus.FAILED; } return(success); }
private bool CopyPDFFromResourceToDocuments(string filename, bool overwrite) { NSFileManager fileManager = new NSFileManager(); string fromPath = NSBundle.MainBundle.PathForResource(filename, "pdf"); if ((fromPath == null) || (fromPath == "")) { return(false); } string toPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), filename + ".pdf"); if (fileManager.FileExists(toPath)) { if (overwrite) { NSError deleteError = null; if (!fileManager.Remove(toPath, out deleteError)) { return(false); } } else { return(false); } } NSError error = null; if (fileManager.Copy(fromPath, toPath, out error)) { return(true); } else { Console.WriteLine("Failed to copy " + filename + ". " + error.LocalizedDescription); return(false); } }
public void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("Finished"); Console.WriteLine("File downloaded in : {0}", location); NSFileManager fileManager = NSFileManager.DefaultManager; var URLs = fileManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); NSUrl documentsDictionry = URLs[0]; NSUrl originalURL = downloadTask.OriginalRequest.Url; NSUrl destinationURL = documentsDictionry.Append("image1.png", false); NSError removeCopy; NSError errorCopy; fileManager.Remove(destinationURL, out removeCopy); bool success = fileManager.Copy(location, destinationURL, out errorCopy); if (success) { // we do not need to be on the main/UI thread to load the UIImage UIImage image = UIImage.FromFile(destinationURL.Path); InvokeOnMainThread(() => { Console.WriteLine("Image downloaded successfully."); var screen = UIScreen.MainScreen.Bounds; UIImageView imageView = new UIImageView(); imageView.Image = image; imageView.Frame = new CGRect(0, 0, screen.Size.Width, screen.Size.Height); controller.Add(imageView); Console.WriteLine("Added image to ImageView"); }); } else { Console.WriteLine("Error during the copy: {0}", errorCopy.LocalizedDescription); } }
static Task <NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl) { var tcs = new TaskCompletionSource <NSUrl>(); NSUrl localDocDir = GetDocumentDirectoryUrl(); NSUrl toURL = localDocDir.Append(fromUrl.LastPathComponent, false); bool success = false; NSError coordinationError, copyError = null; NSFileCoordinator fileCoordinator = new NSFileCoordinator(); ThreadPool.QueueUserWorkItem(_ => { fileCoordinator.CoordinateReadWrite(fromUrl, 0, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out coordinationError, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out copyError); if (success) { var attributes = new NSFileAttributes { FileExtensionHidden = true }; fileManager.SetAttributes(attributes, dst.Path); Console.WriteLine("Copied file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) { Console.WriteLine("Couldn't copy file: {0} to: {1}. Error: {2}.", fromUrl.AbsoluteString, toURL.AbsoluteString, (coordinationError ?? copyError).Description); } tcs.SetResult(toURL); }); return(tcs.Task); }
public static void Completed(NSUrlSessionTask downloadTask, NSUrl location) { NSFileManager fileManager = NSFileManager.DefaultManager; var url = downloadTask.OriginalRequest.Url.AbsoluteString; NSError errorCopy = null; if (Files.ContainsKey(url)) { var file = Files [url]; file.Status = BackgroundDownloadFile.FileStatus.Completed; file.Percent = 1; NSUrl originalURL = downloadTask.OriginalRequest.Url; NSUrl destinationURL = NSUrl.FromFilename(file.Destination); NSError removeCopy; fileManager.Remove(destinationURL, out removeCopy); var success = fileManager.Copy(location, destinationURL, out errorCopy); Console.WriteLine("Success: {0}", success); } else { Console.WriteLine("Could not find the file!"); } TaskCompletionSource <bool> t; if (Tasks.TryGetValue(url, out t)) { if (errorCopy == null) { if (!t.TrySetResult(true)) { Console.WriteLine("ERROR"); } } else { var file = Files [url]; file.Status = BackgroundDownloadFile.FileStatus.Error; file.Error = string.Format("Error during the copy: {0}", errorCopy.LocalizedDescription); t.TrySetException(new Exception(file.Error)); } BackgroundDownloadManager.Tasks.Remove(url); } RemoveUrl(url); saveState(); Console.WriteLine("Tasks: {0}, Downloads {1}, Controllers {2} ", Tasks.Count, DownloadTasks.Count, Controllers.Count); foreach (var f in Files) { Console.WriteLine(f); } var evt = FileCompleted; if (evt != null) { evt(downloadTask, new CompletedArgs { File = Files [url] }); } if (RemoveCompletedAutomatically) { Remove(url); } }