Friday, July 19, 2013

Xamarin.iOS Tip - Copy File in Bundle to Documents Folder

Very often, you need to attach resources to your application so that you can use them during runtime. For example, you might have an empty database created during development time that you want to use to store the locations coordinates collected when the user is using your application. In order to use that database, when the application is first run on the device, you need to copy it from the application bundle onto the application’s Documents folder.

The following method allows you to specify a file to copy from the application bundle onto the application’s Documents folder:

        private void CopyFileInBundleToDocumentsFolder(
        String filename)
        {
            //---path to Documents folder---
            var documentsFolderPath =
                Environment.GetFolderPath(
                    Environment.SpecialFolder.MyDocuments);

            //---destination path for file in the Documents
            // folder---
            var destinationPath =
                Path.Combine(documentsFolderPath, filename);

            //---path of source file---
            var sourcePath = 
                Path.Combine(NSBundle.MainBundle.BundlePath,
                filename);

            //---print for verfications---
            Console.WriteLine(destinationPath);
            Console.WriteLine(sourcePath);

            try {
                //---copy only if file does not exist---
                if (!File.Exists(destinationPath))
                {
                    File.Copy(sourcePath, destinationPath);
                }  else {
                    Console.WriteLine("File already exists");
                }
            }  catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }

You typically call this method when the application is first launched:

        public override bool FinishedLaunching (
        UIApplication app, NSDictionary options)
        {
            window = new UIWindow
                (UIScreen.MainScreen.Bounds);
           
            viewController = new
                BundledResourcesViewController ();
            window.RootViewController = viewController;
            window.MakeKeyAndVisible ();

            //---copy file in bundle to documents folder---
            CopyFileInBundleToDocumentsFolder("MyDB.sql");

            return true;

        }

No comments: