Esempio n. 1
0
        /// <summary>
        /// Gets the files in the current folder.
        /// </summary>
        /// <returns></returns>
        public Task <IReadOnlyList <StorageFile> > GetFilesAsync()
        {
#if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE
            return(Task.Run <IReadOnlyList <StorageFile> >(async() =>
            {
                List <StorageFile> files = new List <StorageFile>();
                var found = await _folder.GetFilesAsync();
                foreach (var file in found)
                {
                    files.Add(file);
                }

                return files.AsReadOnly();
            }));
#elif __ANDROID__ || __UNIFIED__ || WIN32 || TIZEN
            return(Task.Run <IReadOnlyList <StorageFile> >(() =>
            {
                List <StorageFile> files = new List <StorageFile>();

                foreach (string filename in global::System.IO.Directory.GetFiles(Path))
                {
                    files.Add(new StorageFile(global::System.IO.Path.Combine(Path, filename)));
                }

                return files;
            }));
#else
            throw new PlatformNotSupportedException();
#endif
        }
Esempio n. 2
0
        private void ButtonRefresh_Onclick(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var files = storageFolder.GetFilesAsync().GetAwaiter().GetResult();

            Debug.WriteLine(files);
        }
        public async Task When_GetItems()
        {
            var realFileList = await _folderForTestFiles.GetFilesAsync();

            if (realFileList.Count != _filenames.Length)
            {
                Assert.Fail("Number of files mismatch");
            }

            foreach (string requestedFilename in _filenames)
            {
                bool fileOK = realFileList.Any(r => r.Name.Equals(requestedFilename, StringComparison.OrdinalIgnoreCase));
                Assert.IsTrue(fileOK, "Required file is missing - error in tested method");
            }

            var realFolderList = await _folderForTestFiles.GetFoldersAsync();

            if (realFolderList.Count != _foldernames.Length)
            {
                Assert.Fail("Number of folders mismatch");
            }

            foreach (var requestedFoldername in _foldernames)
            {
                bool fileOK = realFolderList.Any(r => r.Name.Equals(requestedFoldername, StringComparison.OrdinalIgnoreCase));
                Assert.IsTrue(fileOK, "Required folder is missing - error in tested method");
            }
        }
Esempio n. 4
0
        public Note()
        {
            this.InitializeComponent();
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var files = storageFolder.GetFilesAsync().GetAwaiter().GetResult();

            if (files == null)
            {
                return;
            }
            this.listNotezzz = new ObservableCollection <NoteItem>();
            for (int i = 0; i < files.Count; i++)
            {
                //var a = new Button();
                //a.Content = files[i].Name;
                //a.Click +=  (s, e) => {
                //    var button = s as Button;
                //    var note = ReadNoteFromLocalStorage(button.Content.ToString());
                //    this.noteEdit.Text = note;
                //};
                //this.menu.Children.Add(a);
                this.listNotezzz.Add(new NoteItem()
                {
                    nameFile = files[i].Name
                });
            }
        }
Esempio n. 5
0
        public async Task <List <string> > GetApplicationDataFromStorageAsync()
        {
            FilesList.Clear();
            var dataFile = await _localFolder.GetFilesAsync();

            foreach (var data in dataFile)
            {
                var text = await Windows.Storage.FileIO.ReadTextAsync(data);

                FilesList.Add(text);
            }
            return(FilesList);
        }
Esempio n. 6
0
        public async System.Threading.Tasks.Task Refresh()
        {
            Windows.Storage.StorageFolder fLocal = Windows.Storage.ApplicationData.Current.LocalCacheFolder;
            IReadOnlyList <Windows.Storage.StorageFile> files = await fLocal.GetFilesAsync();

            this.logfiles.Clear();
            foreach (Windows.Storage.StorageFile lfile in files)
            {
                this.logfiles.Add(new LogFile()
                {
                    file = lfile, label = this.get_location(lfile), ds = lfile.DateCreated.ToString("ddd, d MMM yyyy, HH:mm")
                });
            }
        }
Esempio n. 7
0
        async void ShowFilesAsync()
        {
            //StorageFolder object that represent music folder
            Windows.Storage.StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;


            //Get a list of file in the folder
            //Asynchronous API
            //IReadOnlyList<Windows.Storage.StorageFile> files = await folder.GetFilesAsync();
            files = await folder.GetFilesAsync();


            //Sort by extention name and get file name only
            IEnumerable <string> fileNames = files.OrderBy(f => f.FileType).Select(f => f.Name);

            //Display file names inside of Listview block named "DisplaySongListHere".
            AllLocalSongsListView.ItemsSource = fileNames;
        }
Esempio n. 8
0
        public static async Task CleanStorage(IEnumerable <string> validKeys)
        {
            try
            {
                HashSet <string> keys = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                keys.UnionWith(validKeys);
                Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                var files = await localFolder.GetFilesAsync();

                foreach (var f in files)
                {
                    if (!keys.Contains(System.IO.Path.GetFileNameWithoutExtension(f.Path)))
                    {
                        await f.DeleteAsync();
                    }
                }
            }
            catch // nothrow
            { }
        }
Esempio n. 9
0
        public static async Task <BookContainer> GetFromStorageFolder(Windows.Storage.StorageFolder folder, string Token = null, string[] Path = null)
        {
            var result = new BookContainer();

            result.Title = folder.DisplayName;

            List <string> path = (Path ?? new string[0]).ToList();

            if (Token == null)
            {
                Token = Books.BookManager.StorageItemRegister(folder);
            }
            else
            {
                path.Add(folder.Name);
            }

            foreach (var item in await folder.GetFoldersAsync())
            {
                var f = await GetFromStorageFolder(item, Token, path.ToArray());

                if (!f.IsEmpty())
                {
                    result.Folders.Add(f);
                }
            }

            foreach (var item in await folder.GetFilesAsync())
            {
                var f = await GetFromStorageFile(item, Token, path.ToArray());

                if (f != null)
                {
                    result.Files.Add(f);
                }
            }

            return(result);
        }
Esempio n. 10
0
        public static async System.Threading.Tasks.Task LoadPhotoTask(string size, string name)
        {
            Windows.Storage.StorageFolder installationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            Windows.Storage.StorageFolder assetsFolder       = await installationFolder.GetFolderAsync("Assets");

            Windows.Storage.StorageFolder imagesFolder = await assetsFolder.GetFolderAsync("Images");

            Windows.Storage.StorageFolder sizeFolder = null;
            if (size.Equals("0.3MP"))
            {
                sizeFolder = await imagesFolder.GetFolderAsync("0_3mp");
            }
            else
            {
                sizeFolder = await imagesFolder.GetFolderAsync(size.ToLower());
            }

            IReadOnlyList <Windows.Storage.StorageFile> files = await sizeFolder.GetFilesAsync();

            foreach (var file in files)
            {
                if (name.Equals(file.Name))
                {
                    using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenReadAsync())
                    {
                        ImageJpg = new byte[fileStream.Size];
                        using (var reader = new Windows.Storage.Streams.DataReader(await file.OpenReadAsync()))
                        {
                            await reader.LoadAsync((uint)fileStream.Size);

                            reader.ReadBytes(ImageJpg);
                        }
                    }
                    break;
                }
            }
        }
Esempio n. 11
0
                private async Task <NetworkStatus> VerifyFolder()
                {
                    Status = NetworkStatus.Networking;
                    long currentProgress = 0, totalProgress = 1;

                    OnProgressChanged(currentProgress, totalProgress);
                    if (cloudFolder.Name != windowsFolder.Name)
                    {
                        OnMessageAppended($"Name not consistent, Cloud: {cloudFolder.Name}, Local: {windowsFolder.Name}");
                        return(NetworkStatus.ErrorNeedRestart);
                    }
                    var folderVerifiers = new List <Tuple <CloudFile, Windows.Storage.StorageFolder> >();

                    {
                        if (!await GetCloudSubFolders())
                        {
                            return(NetworkStatus.ErrorNeedRestart);
                        }
                        Dictionary <string, Windows.Storage.StorageFolder> localSubFolders = new Dictionary <string, Windows.Storage.StorageFolder>();
                        foreach (var f in await windowsFolder.GetFoldersAsync())
                        {
                            if (!cloudSubFolders.ContainsKey(f.Name))
                            {
                                OnMessageAppended($"Cloud Folder doesn't exist: {f.Name}");
                                return(NetworkStatus.ErrorNeedRestart);
                            }
                            localSubFolders.Add(f.Name, f);
                        }
                        foreach (var p in cloudSubFolders)
                        {
                            if (!localSubFolders.ContainsKey(p.Key))
                            {
                                OnMessageAppended($"Local Folder doesn't exist: {p.Key}");
                                return(NetworkStatus.ErrorNeedRestart);
                            }
                            folderVerifiers.Add(new Tuple <CloudFile, Windows.Storage.StorageFolder>(p.Value, localSubFolders[p.Key]));
                            localSubFolders.Remove(p.Key);
                        }
                        MyLogger.Assert(localSubFolders.Count == 0);
                    }
                    {
                        if (!await GetCloudSubFiles())
                        {
                            return(NetworkStatus.ErrorNeedRestart);
                        }
                        Dictionary <string, Windows.Storage.StorageFile> localSubFiles = new Dictionary <string, Windows.Storage.StorageFile>();
                        foreach (var f in await windowsFolder.GetFilesAsync())
                        {
                            if (!cloudSubFiles.ContainsKey(f.Name))
                            {
                                OnMessageAppended($"Cloud File doesn't exist: {f.Name}");
                                return(NetworkStatus.ErrorNeedRestart);
                            }
                            localSubFiles.Add(f.Name, f);
                        }
                        foreach (var p in cloudSubFiles)
                        {
                            if (!localSubFiles.ContainsKey(p.Key))
                            {
                                OnMessageAppended($"Local File doesn't exist: {p.Key}");
                                return(NetworkStatus.ErrorNeedRestart);
                            }
                        }
                        OnProgressChanged(++currentProgress, totalProgress += cloudSubFiles.Count);
                        CurrentProgressChanged?.Invoke(1);
                        TotalProgressChanged?.Invoke(cloudSubFiles.Count);
                        OnMessageAppended("Verifying subfiles...");
                        int filesVerified = 0;
                        foreach (var p in cloudSubFiles)
                        {
                            var localFile = localSubFiles[p.Key];
                            var stream    = await localFile.OpenStreamForReadAsync();

                            var localMd5 = await Libraries.GetSha256ForWindowsStorageFile(stream);

                            stream.Dispose();
                            if (localMd5 != p.Value || p.Value == null)
                            {
                                OnMessageAppended($"{p.Key} content not consistent, Cloud: {p.Value}, Local: {localMd5}");
                                CurrentProgressChanged?.Invoke(-filesVerified - 1);
                                TotalProgressChanged?.Invoke(-cloudSubFiles.Count);
                                return(NetworkStatus.ErrorNeedRestart);
                            }
                            OnProgressChanged(++currentProgress, totalProgress);
                            CurrentProgressChanged?.Invoke(1);
                            ++filesVerified;
                            localSubFiles.Remove(p.Key);
                        }
                        OnMessageAppended("Subfiles verified.");
                        MyLogger.Assert(localSubFiles.Count == 0);
                    }
                    OnProgressChanged(currentProgress, totalProgress += folderVerifiers.Count);
                    TotalProgressChanged?.Invoke(folderVerifiers.Count);
                    ReleaseSemaphoreSlim();
                    OnMessageAppended("Waiting for subfolders to be verified...");
                    try
                    {
                        await Task.WhenAll(folderVerifiers.Select(async(tuple) =>
                        {
                            var totalProgressChangedEventHandler = new TotalProgressChangedEventHandler((difference) =>
                            {
                                OnProgressChanged(currentProgress, totalProgress += difference);
                                TotalProgressChanged?.Invoke(difference);
                            });
                            var currentProgressChangedEventHandler = new TotalProgressChangedEventHandler((difference) =>
                            {
                                //MyLogger.Assert(difference == 1);
                                OnProgressChanged(currentProgress += difference, totalProgress);
                                CurrentProgressChanged?.Invoke(difference);
                            });
                            var verifier = new Verifiers.FolderVerifier(tuple.Item1, tuple.Item2);
                            verifier.TotalProgressChanged   += totalProgressChangedEventHandler;
                            verifier.CurrentProgressChanged += currentProgressChangedEventHandler;
                            await verifier.StartUntilCompletedAsync();
                            verifier.TotalProgressChanged   -= totalProgressChangedEventHandler;
                            verifier.CurrentProgressChanged -= currentProgressChangedEventHandler;
                        }));

                        return(NetworkStatus.Completed);
                    }
                    finally
                    {
                        await WaitSemaphoreSlimAsync();
                    }
                }
Esempio n. 12
0
        /// <summary>
        /// Attemps to load opencv modules from the specific location
        /// </summary>
        /// <param name="loadDirectory">The directory where the unmanaged modules will be loaded. If it is null, the default location will be used.</param>
        /// <param name="unmanagedModules">The names of opencv modules. e.g. "opencv_cxcore.dll" on windows.</param>
        /// <returns>True if all the modules has been loaded sucessfully</returns>
        /// <remarks>If <paramref name="loadDirectory"/> is null, the default location on windows is the dll's path appended by either "x64" or "x86", depends on the applications current mode.</remarks>
        public static bool LoadUnmanagedModules(String loadDirectory, params String[] unmanagedModules)
        {
#if NETFX_CORE
            if (loadDirectory != null)
            {
                throw new NotImplementedException("Loading modules from a specific directory is not implemented in Windows Store App");
            }

            String subfolder = String.Empty;
            if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows)
            {
                if (IntPtr.Size == 8)
                { //64bit process
                    subfolder = "x64";
                }
                else
                {
                    subfolder = "x86";
                }
            }

            Windows.Storage.StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            loadDirectory = Path.Combine(installFolder.Path, subfolder);

            var t = System.Threading.Tasks.Task.Run(async() =>
            {
                Windows.Storage.StorageFolder loadFolder = await installFolder.GetFolderAsync(subfolder);
                List <string> files = new List <string>();
                foreach (var file in await loadFolder.GetFilesAsync())
                {
                    files.Add(file.Path);
                }
                return(files);
            });
            t.Wait();

            List <String> loadableFiles = t.Result;
#else
            if (loadDirectory == null)
            {
                String subfolder = String.Empty;
                if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows)
                {
                    subfolder = IntPtr.Size == 8 ? "x64" : "x86";
                }

                /*
                 * else if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.MacOSX)
                 * {
                 * subfolder = "..";
                 * }*/

                System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
                FileInfo file = new FileInfo(asm.Location);
                //FileInfo file = new FileInfo(asm.CodeBase);
                DirectoryInfo directory = file.Directory;
                loadDirectory = directory.FullName;

                if (!String.IsNullOrEmpty(subfolder))
                {
                    loadDirectory = Path.Combine(loadDirectory, subfolder);
                }

                if (!Directory.Exists(loadDirectory))
                {
                    //try to find an alternative loadDirectory path
                    //The following code should handle finding the asp.NET BIN folder
                    String altLoadDirectory = Path.GetDirectoryName(asm.CodeBase);
                    if (altLoadDirectory.StartsWith(@"file:\"))
                    {
                        altLoadDirectory = altLoadDirectory.Substring(6);
                    }

                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        altLoadDirectory = Path.Combine(altLoadDirectory, subfolder);
                    }

                    if (!Directory.Exists(altLoadDirectory))
                    {
                        return(false);
                    }
                    else
                    {
                        loadDirectory = altLoadDirectory;
                    }
                }
            }

            String oldDir = Environment.CurrentDirectory;
            Environment.CurrentDirectory = loadDirectory;
#endif
            bool success = true;

            string prefix = string.Empty;

            foreach (String module in unmanagedModules)
            {
                string mName = module;

                //handle special case for universal build
                if (
                    mName.StartsWith("opencv_ffmpeg") && //opencv_ffmpegvvv(_64).dll
                    (IntPtr.Size == 4) //32bit application
                    )
                {
                    mName = module.Replace("_64", String.Empty);
                }

                String fullPath = Path.Combine(loadDirectory, Path.Combine(prefix, mName));

#if NETFX_CORE
                if (loadableFiles.Exists(sf => sf.Equals(fullPath)))
                {
                    IntPtr handle = Toolbox.LoadLibrary(fullPath);
                    success &= (!IntPtr.Zero.Equals(handle));
                }
                else
                {
                    success = false;
                }
#else
                success &= (File.Exists(fullPath) && !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath)));
#endif
            }

#if !NETFX_CORE
            Environment.CurrentDirectory = oldDir;
#endif
            return(success);
        }
Esempio n. 13
0
        /// <summary>
        /// Attempts to load opencv modules from the specific location
        /// </summary>
        /// <param name="loadDirectory">The directory where the unmanaged modules will be loaded. If it is null, the default location will be used.</param>
        /// <param name="unmanagedModules">The names of opencv modules. e.g. "opencv_cxcore.dll" on windows.</param>
        /// <returns>True if all the modules has been loaded successfully</returns>
        /// <remarks>If <paramref name="loadDirectory"/> is null, the default location on windows is the dll's path appended by either "x64" or "x86", depends on the applications current mode.</remarks>
        public static bool LoadUnmanagedModules(String loadDirectory, params String[] unmanagedModules)
        {
#if NETFX_CORE
            if (loadDirectory != null)
            {
                throw new NotImplementedException("Loading modules from a specific directory is not implemented in Windows Store App");
            }

            String subfolder = String.Empty;
            if (Emgu.Util.Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows) //|| Platform.OperationSystem == Emgu.Util.TypeEnum.OS.WindowsPhone)
            {
                if (IntPtr.Size == 8)
                { //64bit process
#if UNITY_METRO
                    subfolder = "x86_64";
#else
                    subfolder = String.Empty;
#endif
                }
                else
                {
                    subfolder = String.Empty;
                }
            }

            Windows.Storage.StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

#if UNITY_METRO
            loadDirectory = Path.Combine(
                Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(installFolder.Path))))
                , "Plugins", "Metro", subfolder);
#else
            loadDirectory = Path.Combine(installFolder.Path, subfolder);
#endif

            var t = System.Threading.Tasks.Task.Run(async() =>
            {
                List <string> files = new List <string>();
                Windows.Storage.StorageFolder loadFolder = installFolder;
                try
                {
                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        loadFolder = await installFolder.GetFolderAsync(subfolder);
                    }

                    foreach (var file in await loadFolder.GetFilesAsync())
                    {
                        files.Add(file.Name);
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Unable to retrieve files in folder '{0}':{1}", loadFolder.Path, e.StackTrace));
                }

                return(files);
            });
            t.Wait();

            List <String> loadableFiles = t.Result;
#else
            if (loadDirectory == null)
            {
                String subfolder = String.Empty;
#if UNITY_EDITOR_WIN
                subfolder = IntPtr.Size == 8 ? "x86_64" : "x86";
#elif UNITY_STANDALONE_WIN
#else
                if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows)
                {
                    subfolder = IntPtr.Size == 8 ? "x64" : "x86";
                }
#endif

                /*
                 * else if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.MacOSX)
                 * {
                 * subfolder = "..";
                 * }*/
#if NETSTANDARD1_4
                loadDirectory = new DirectoryInfo(".").FullName;
#else
                System.Reflection.Assembly asm = typeof(CvInvoke).Assembly; //System.Reflection.Assembly.GetExecutingAssembly();
                if ((String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location)) && AppDomain.CurrentDomain.BaseDirectory != null)
                {
                    //if may be running in a debugger visualizer under a unit test in this case
                    String        visualStudioDir       = AppDomain.CurrentDomain.BaseDirectory;
                    DirectoryInfo visualStudioDirInfo   = new DirectoryInfo(visualStudioDir);
                    String        debuggerVisualzerPath =
                        Path.Combine(Path.Combine(Path.Combine(
                                                      visualStudioDirInfo.Parent.FullName, "Packages"), "Debugger"), "Visualizers");

                    if (Directory.Exists(debuggerVisualzerPath))
                    {
                        loadDirectory = debuggerVisualzerPath;
                    }
                    else
                    {
                        loadDirectory = String.Empty;
                    }

/*
 *             loadDirectory = Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path);
 *
 *             DirectoryInfo dir = new DirectoryInfo(loadDirectory);
 *             string subdir = String.Join(";", Array.ConvertAll(dir.GetDirectories(), d => d.ToString()));
 *
 *             throw new Exception(String.Format(
 *                "The Emgu.CV.dll assembly path (typeof (CvInvoke).Assembly.Location) '{0}' is invalid." +
 *                Environment.NewLine
 + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().Location): '{1}';" +
 +                Environment.NewLine
 + " Other possible path (Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path): '{2}';" +
 +                Environment.NewLine
 + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().CodeBase): '{3};'" +
 +                Environment.NewLine
 + " Other possible path (typeof(CvInvoke).Assembly.CodeBase): '{4}'" +
 +                Environment.NewLine
 + " Other possible path (AppDomain.CurrentDomain.BaseDirectory): '{5}'" +
 +                Environment.NewLine
 + " subfolder name: '{6}'",
 +                asm.Location,
 +                Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path),
 +                loadDirectory + ": subdir '" + subdir +"'",
 +                System.Reflection.Assembly.GetExecutingAssembly().CodeBase,
 +                typeof(CvInvoke).Assembly.Location,
 +                AppDomain.CurrentDomain.BaseDirectory,
 +                subfolder
 +                ));
 */
                }
                else
                {
                    loadDirectory = Path.GetDirectoryName(asm.Location);
                }

                /*
                 * FileInfo file = new FileInfo(asm.Location);
                 * //FileInfo file = new FileInfo(asm.CodeBase);
                 * DirectoryInfo directory = file.Directory;
                 * loadDirectory = directory.FullName;
                 */
#endif
                if (!String.IsNullOrEmpty(subfolder))
                {
                    var temp = Path.Combine(loadDirectory, subfolder);
                    if (Directory.Exists(temp))
                    {
                        loadDirectory = temp;
                    }
                    else
                    {
                        loadDirectory = Path.Combine(Path.GetFullPath("."), subfolder);
                    }
                }

#if (UNITY_STANDALONE_WIN && !UNITY_EDITOR_WIN)
                if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))
                {
                    Debug.WriteLine(String.Format("UNITY_STANDALONE_WIN: asm.Location is invalid: '{0}'", asm.Location));
                    return(false);
                }


                FileInfo      file      = new FileInfo(asm.Location);
                DirectoryInfo directory = file.Directory;
                if (directory.Parent != null)
                {
                    String unityAltFolder = Path.Combine(directory.Parent.FullName, "Plugins");

                    if (Directory.Exists(unityAltFolder))
                    {
                        loadDirectory = unityAltFolder;
                    }
                    else
                    {
                        Debug.WriteLine("No suitable directory found to load unmanaged modules");
                        return(false);
                    }
                }
#elif __ANDROID__ || UNITY_ANDROID || NETSTANDARD1_4
#else
                if (!Directory.Exists(loadDirectory))
                {
                    //try to find an alternative loadDirectory path
                    //The following code should handle finding the asp.NET BIN folder
                    String altLoadDirectory = Path.GetDirectoryName(asm.CodeBase);
                    if (!String.IsNullOrEmpty(altLoadDirectory) && altLoadDirectory.StartsWith(@"file:\"))
                    {
                        altLoadDirectory = altLoadDirectory.Substring(6);
                    }

                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        altLoadDirectory = Path.Combine(altLoadDirectory, subfolder);
                    }

                    if (!Directory.Exists(altLoadDirectory))
                    {
                        if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))
                        {
                            Debug.WriteLine(String.Format("asm.Location is invalid: '{0}'", asm.Location));
                            return(false);
                        }
                        FileInfo      file      = new FileInfo(asm.Location);
                        DirectoryInfo directory = file.Directory;
#if UNITY_EDITOR_WIN
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(
                                    Path.Combine(Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Emgu.CV"), "Plugins"),
                                    subfolder);

                            Debug.WriteLine("Trying unityAltFolder: " + unityAltFolder);
                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                Debug.WriteLine("No suitable directory found to load unmanaged modules");
                                return(false);
                            }
                        }
                        else
#elif (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX)
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(Path.Combine(Path.Combine(
                                                              Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Plugins"),
                                                              "emgucv.bundle"), "Contents"), "MacOS");

                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
#endif
                        {
                            Debug.WriteLine("No suitable directory found to load unmanaged modules");
                            return(false);
                        }
                    }
                    else
                    {
                        loadDirectory = altLoadDirectory;
                    }
                }
#endif
            }
#if !(NETSTANDARD1_4)
            String oldDir = Environment.CurrentDirectory;
            if (!String.IsNullOrEmpty(loadDirectory) && Directory.Exists(loadDirectory))
            {
                Environment.CurrentDirectory = loadDirectory;
            }
#endif
#endif

            System.Diagnostics.Debug.WriteLine(String.Format("Loading open cv binary from {0}", loadDirectory));
            bool success = true;

            string prefix = string.Empty;

            foreach (String module in unmanagedModules)
            {
                string mName = module;

                //handle special case for universal build
                if (
                    mName.StartsWith("opencv_ffmpeg") && //opencv_ffmpegvvv(_64).dll
                    (IntPtr.Size == 4) //32bit application
                    )
                {
                    mName = module.Replace("_64", String.Empty);
                }

                String fullPath = Path.Combine(prefix, mName);

#if NETFX_CORE
                if (loadableFiles.Exists(sf => sf.Equals(fullPath)))
                {
                    IntPtr handle = Toolbox.LoadLibrary(fullPath);
                    success &= (!IntPtr.Zero.Equals(handle));
                }
                else
                {
                    success = false;
                }
#else
                //Use absolute path for Windows Desktop
                fullPath = Path.Combine(loadDirectory, fullPath);

                bool fileExist = File.Exists(fullPath);
                if (!fileExist)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("File {0} do not exist.", fullPath));
                }
                bool fileExistAndLoaded = fileExist && !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath));
                if (fileExist && (!fileExistAndLoaded))
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("File {0} cannot be loaded.", fullPath));
                }
                success &= fileExistAndLoaded;
#endif
            }

#if !(NETFX_CORE || NETSTANDARD1_4)
            Environment.CurrentDirectory = oldDir;
#endif
            return(success);
        }
Esempio n. 14
0
        /// <summary>
        /// Attempts to load opencv modules from the specific location
        /// </summary>
        /// <param name="loadDirectory">The directory where the unmanaged modules will be loaded. If it is null, the default location will be used.</param>
        /// <param name="unmanagedModules">The names of opencv modules. e.g. "opencv_cxcore.dll" on windows.</param>
        /// <returns>True if all the modules has been loaded successfully</returns>
        /// <remarks>If <paramref name="loadDirectory"/> is null, the default location on windows is the dll's path appended by either "x64" or "x86", depends on the applications current mode.</remarks>
        public static bool LoadUnmanagedModules(String loadDirectory, params String[] unmanagedModules)
        {
#if NETFX_CORE
            if (loadDirectory != null)
            {
                throw new NotImplementedException("Loading modules from a specific directory is not implemented in Windows Store App");
            }

            String subfolder = String.Empty;
            if (Emgu.Util.Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows) //|| Platform.OperationSystem == Emgu.Util.TypeEnum.OS.WindowsPhone)
            {
                if (IntPtr.Size == 8)
                { //64bit process
#if UNITY_METRO
                    subfolder = "x86_64";
#else
                    subfolder = String.Empty;
#endif
                }
                else
                {
                    subfolder = String.Empty;
                }
            }

            Windows.Storage.StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

#if UNITY_METRO
            loadDirectory = Path.Combine(
                Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(installFolder.Path))))
                , "Plugins", "Metro", subfolder);
#else
            loadDirectory = Path.Combine(installFolder.Path, subfolder);
#endif

            var t = System.Threading.Tasks.Task.Run(async() =>
            {
                List <string> files = new List <string>();
                Windows.Storage.StorageFolder loadFolder = installFolder;
                try
                {
                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        loadFolder = await installFolder.GetFolderAsync(subfolder);
                    }

                    foreach (var file in await loadFolder.GetFilesAsync())
                    {
                        files.Add(file.Name);
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Unable to retrieve files in folder '{0}':{1}", loadFolder.Path, e.StackTrace));
                }

                return(files);
            });
            t.Wait();

            List <String> loadableFiles = t.Result;
#else
            if (loadDirectory == null)
            {
                String subfolder = String.Empty;
#if UNITY_EDITOR_WIN
                subfolder = IntPtr.Size == 8 ? "x86_64" : "x86";
#elif UNITY_STANDALONE_WIN
#else
                if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows)
                {
                    subfolder = IntPtr.Size == 8 ? "x64" : "x86";
                }
#endif

                /*
                 * else if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.MacOSX)
                 * {
                 * subfolder = "..";
                 * }*/

                System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
                FileInfo file = new FileInfo(asm.Location);
                //FileInfo file = new FileInfo(asm.CodeBase);
                DirectoryInfo directory = file.Directory;
                loadDirectory = directory.FullName;

                if (!String.IsNullOrEmpty(subfolder))
                {
                    loadDirectory = Path.Combine(loadDirectory, subfolder);
                }

#if (UNITY_STANDALONE_WIN && !UNITY_EDITOR_WIN)
                if (directory.Parent != null)
                {
                    String unityAltFolder = Path.Combine(directory.Parent.FullName, "Plugins");

                    if (Directory.Exists(unityAltFolder))
                    {
                        loadDirectory = unityAltFolder;
                    }
                    else
                    {
                        Debug.WriteLine("No suitable directory found to load unmanaged modules");
                        return(false);
                    }
                }
#else
                if (!Directory.Exists(loadDirectory))
                {
                    //try to find an alternative loadDirectory path
                    //The following code should handle finding the asp.NET BIN folder
                    String altLoadDirectory = Path.GetDirectoryName(asm.CodeBase);
                    if (altLoadDirectory.StartsWith(@"file:\"))
                    {
                        altLoadDirectory = altLoadDirectory.Substring(6);
                    }

                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        altLoadDirectory = Path.Combine(altLoadDirectory, subfolder);
                    }

                    if (!Directory.Exists(altLoadDirectory))
                    {
#if UNITY_EDITOR_WIN
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(
                                    Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Plugins"),
                                    subfolder);

                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                Debug.WriteLine("No suitable directory found to load unmanaged modules");
                                return(false);
                            }
                        }
                        else
#elif (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX)
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(Path.Combine(Path.Combine(
                                                              Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Plugins"),
                                                              "emgucv.bundle"), "Contents"), "MacOS");

                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
#endif
                        {
                            Debug.WriteLine("No suitable directory found to load unmanaged modules");
                            return(false);
                        }
                    }
                    else
                    {
                        loadDirectory = altLoadDirectory;
                    }
                }
#endif
            }

            String oldDir = Environment.CurrentDirectory;
            Environment.CurrentDirectory = loadDirectory;
#endif

            System.Diagnostics.Debug.WriteLine(String.Format("Loading open cv binary from {0}", loadDirectory));
            bool success = true;

            string prefix = string.Empty;

            foreach (String module in unmanagedModules)
            {
                string mName = module;

                //handle special case for universal build
                if (
                    mName.StartsWith("opencv_ffmpeg") && //opencv_ffmpegvvv(_64).dll
                    (IntPtr.Size == 4) //32bit application
                    )
                {
                    mName = module.Replace("_64", String.Empty);
                }

                String fullPath = Path.Combine(prefix, mName);

                /*
                 * if (Emgu.Util.Platform.OperationSystem != Emgu.Util.TypeEnum.OS.WindowsPhone)
                 * {
                 * //Do not use absolute path for Windows Phone
                 * fullPath = Path.Combine(loadDirectory, fullPath);
                 * }*/

#if NETFX_CORE
                if (loadableFiles.Exists(sf => sf.Equals(fullPath)))
                {
                    IntPtr handle = Toolbox.LoadLibrary(fullPath);
                    success &= (!IntPtr.Zero.Equals(handle));
                }
                else
                {
                    success = false;
                }
#else
                bool fileExist = File.Exists(fullPath);
                if (!fileExist)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("File {0} do not exist.", fullPath));
                }
                bool fileExistAndLoaded = fileExist && !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath));
                if (fileExist && (!fileExistAndLoaded))
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("File {0} cannot be loaded.", fullPath));
                }
                success &= fileExistAndLoaded;
#endif
            }

#if !NETFX_CORE
            Environment.CurrentDirectory = oldDir;
#endif
            return(success);
        }
Esempio n. 15
0
        protected async static Task <string []> GetFileNamesAsync(Windows.Storage.StorageFolder fldr, string wildcard)
        {
            //
            // NOT WORKING!!!
            //

            /*
             * else
             * {
             *      using Windows.Storage.Search;
             *
             *      if( !fldr.IsCommonFileQuerySupported( CommonFileQuery.DefaultQuery ) )
             *              throw new Exception( "Unable to query!" );
             *
             *      /*
             *      string sTypeFilter = "*";
             *      if( sSearchPattern.IndexOf( "*." ) == 0 )
             *              sTypeFilter = sSearchPattern.Substring( 1 );
             *      else
             *              sTypeFilter = sSearchPattern; //This mustn't working...
             *
             *
             *      List<string> lstTypeFilter = new List<string>();
             *      lstTypeFilter.Add("*");
             *
             *      //QueryOptions queryOptions = new QueryOptions(); //CommonFileQuery.DefaultQuery); //, lstTypeFilter);
             *      //queryOptions.UserSearchFilter = sSearchPattern;
             *
             *      QueryOptions queryOptions = new QueryOptions();
             *      queryOptions.FolderDepth = Windows.Storage.Search.FolderDepth.Deep;
             *      queryOptions.IndexerOption = Windows.Storage.Search.IndexerOption.UseIndexerWhenAvailable;
             *      //queryOptions.UserSearchFilter = "'" + sSearchPattern + "'";
             *
             *      //"'" + Begriff + @"' folder:" + Ordner
             *      //"last quarter" author:(theresa OR lee) folder:MyDocs
             *
             *      StorageFileQueryResult queryResult = fldr.CreateFileQueryWithOptions(queryOptions);
             *
             *      IReadOnlyList<StorageFile> subfiles = await queryResult.GetFilesAsync();
             *
             *      astr = new String[ subfiles.Count ];
             *      int i = 0;
             *      foreach (StorageFile file in subfiles)
             *      {
             *              astr[ i ] = file.Name;
             *              i++;
             *      }
             * }
             */

            IReadOnlyList <Windows.Storage.StorageFile> subfiles =
                await fldr.GetFilesAsync();

            RscWildCard wc = new RscWildCard(wildcard);

            string [] astr = new String[subfiles.Count];

            int iLenSave = astr.Length;
            int i        = 0;

            foreach (Windows.Storage.StorageFile file in subfiles)
            {
                if (wc.Wanted(file.Name))
                {
                    astr[i] = file.Name;
                    i++;
                }
            }

            if (i == 0)
            {
                return new String [] {}
            }
            ;                                                 //All filtered out...
            if (i == iLenSave)
            {
                return(astr);                            //All wanted...
            }
            //Not so nice... :(
            string [] astr2 = new String[i];
            for (int j = 0; j < i; j++)
            {
                astr2[j] = astr[j];
            }

            return(astr2);
        }
Esempio n. 16
0
        public static async void get_loacl_music(Windows.Storage.StorageFolder folder)
        {
            var files = await folder.GetFilesAsync();

            var data = files.ToList();
        }
Esempio n. 17
0
        /// <summary>
        /// Attempts to load opencv modules from the specific location
        /// </summary>
        /// <param name="loadDirectory">The directory where the unmanaged modules will be loaded. If it is null, the default location will be used.</param>
        /// <param name="unmanagedModules">The names of opencv modules. e.g. "opencv_core.dll" on windows.</param>
        /// <returns>True if all the modules has been loaded successfully</returns>
        /// <remarks>If <paramref name="loadDirectory"/> is null, the default location on windows is the dll's path appended by either "x64" or "x86", depends on the applications current mode.</remarks>
        public static bool LoadUnmanagedModules(String loadDirectory, params String[] unmanagedModules)
        {
#if NETFX_CORE
            if (loadDirectory != null)
            {
                throw new NotImplementedException("Loading modules from a specific directory is not implemented in Windows Store App");
            }

            String subfolder = String.Empty;
            if (Emgu.Util.Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows) //|| Platform.OperationSystem == Emgu.Util.TypeEnum.OS.WindowsPhone)
            {
                if (IntPtr.Size == 8)
                { //64bit process
#if UNITY_METRO
                    subfolder = "x86_64";
#else
                    subfolder = String.Empty;
#endif
                }
                else
                {
                    subfolder = String.Empty;
                }
            }

            Windows.Storage.StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

#if UNITY_METRO
            loadDirectory = Path.Combine(
                Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(installFolder.Path))))
                , "Plugins", "Metro", subfolder);
#else
            loadDirectory = Path.Combine(installFolder.Path, subfolder);
#endif

            var t = System.Threading.Tasks.Task.Run(async() =>
            {
                List <string> files = new List <string>();
                Windows.Storage.StorageFolder loadFolder = installFolder;
                try
                {
                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        loadFolder = await installFolder.GetFolderAsync(subfolder);
                    }

                    foreach (var file in await loadFolder.GetFilesAsync())
                    {
                        files.Add(file.Name);
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Unable to retrieve files in folder '{0}':{1}", loadFolder.Path, e.StackTrace));
                }

                return(files);
            });
            t.Wait();

            List <String> loadableFiles = t.Result;
#else
            if (loadDirectory == null)
            {
                String subfolder = String.Empty;
#if UNITY_EDITOR_WIN
                subfolder = IntPtr.Size == 8 ? "x86_64" : "x86";
#elif UNITY_STANDALONE_WIN
#else
                if (Platform.OperationSystem == Emgu.Util.Platform.OS.Windows ||
                    Platform.OperationSystem == Emgu.Util.Platform.OS.Linux)
                {
                    //var fd = RuntimeInformation.FrameworkDescription;
                    if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
                    {
                        subfolder = "x86";
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
                    {
                        subfolder = "x64";
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm)
                    {
                        subfolder = "arm";
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
                    {
                        subfolder = "arm64";
                    }

                    //subfolder = IntPtr.Size == 8 ? "x64" : "x86";
                }
#endif

                System.Reflection.Assembly asm = typeof(CvInvoke).Assembly; //System.Reflection.Assembly.GetExecutingAssembly();
                if ((String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location)))
                {
                    if (String.IsNullOrEmpty(AppDomain.CurrentDomain.BaseDirectory))
                    {
                        loadDirectory = String.Empty;
                    }
                    else
                    {
                        //we may be running in a debugger visualizer under a unit test in this case
                        String        baseDirectory          = AppDomain.CurrentDomain.BaseDirectory;
                        DirectoryInfo baseDirectoryInfo      = new DirectoryInfo(baseDirectory);
                        String        debuggerVisualizerPath = String.Empty;
                        if (baseDirectoryInfo.Parent != null)
                        {
                            debuggerVisualizerPath = Path.Combine(baseDirectoryInfo.Parent.FullName, "Packages", "Debugger", "Visualizers");
                        }

                        if (!debuggerVisualizerPath.Equals(String.Empty) && Directory.Exists(debuggerVisualizerPath))
                        {
                            loadDirectory = debuggerVisualizerPath;
                        }
                        else
                        {
                            loadDirectory = baseDirectoryInfo.FullName;
                            if (!Directory.Exists(Path.Combine(baseDirectoryInfo.FullName, subfolder)))
                            {
                                subfolder = String.Empty;
                            }
                        }

                        /*
                         * loadDirectory = Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path);
                         *
                         * DirectoryInfo dir = new DirectoryInfo(loadDirectory);
                         * string subdir = String.Join(";", Array.ConvertAll(dir.GetDirectories(), d => d.ToString()));
                         *
                         * throw new Exception(String.Format(
                         *    "The Emgu.CV.dll assembly path (typeof (CvInvoke).Assembly.Location) '{0}' is invalid." +
                         *    Environment.NewLine
                         + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().Location): '{1}';" +
                         +    Environment.NewLine
                         + " Other possible path (Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path): '{2}';" +
                         +    Environment.NewLine
                         + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().CodeBase): '{3};'" +
                         +    Environment.NewLine
                         + " Other possible path (typeof(CvInvoke).Assembly.CodeBase): '{4}'" +
                         +    Environment.NewLine
                         + " Other possible path (AppDomain.CurrentDomain.BaseDirectory): '{5}'" +
                         +    Environment.NewLine
                         + " subfolder name: '{6}'",
                         +    asm.Location,
                         +    Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path),
                         +    loadDirectory + ": subdir '" + subdir +"'",
                         +    System.Reflection.Assembly.GetExecutingAssembly().CodeBase,
                         +    typeof(CvInvoke).Assembly.Location,
                         +    AppDomain.CurrentDomain.BaseDirectory,
                         +    subfolder
                         +    ));
                         */
                    }
                }
                else
                {
                    loadDirectory = Path.GetDirectoryName(asm.Location);
                    if ((loadDirectory != null) && (!Directory.Exists(Path.Combine(loadDirectory, subfolder))))
                    {
                        subfolder = String.Empty;
                    }
                }

                /*
                 * FileInfo file = new FileInfo(asm.Location);
                 * //FileInfo file = new FileInfo(asm.CodeBase);
                 * DirectoryInfo directory = file.Directory;
                 * loadDirectory = directory.FullName;
                 */

                if (!String.IsNullOrEmpty(subfolder))
                {
                    var temp = Path.Combine(loadDirectory, subfolder);
                    if (Directory.Exists(temp))
                    {
                        loadDirectory = temp;
                    }
                    else
                    {
                        loadDirectory = Path.Combine(Path.GetFullPath("."), subfolder);
                    }
                }

#if (UNITY_STANDALONE_WIN && !UNITY_EDITOR_WIN)
                if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))
                {
                    Debug.WriteLine(String.Format("UNITY_STANDALONE_WIN: asm.Location is invalid: '{0}'", asm.Location));
                    return(false);
                }


                FileInfo      file      = new FileInfo(asm.Location);
                DirectoryInfo directory = file.Directory;
                if (directory.Parent != null)
                {
                    String unityAltFolder = Path.Combine(directory.Parent.FullName, "Plugins");

                    if (Directory.Exists(unityAltFolder))
                    {
                        loadDirectory = unityAltFolder;
                    }
                    else
                    {
                        Debug.WriteLine("No suitable directory found to load unmanaged modules");
                        return(false);
                    }
                }
#elif UNITY_ANDROID
#else
                if (!Directory.Exists(loadDirectory))
                {
                    //try to find an alternative loadDirectory path
                    //The following code should handle finding the asp.NET BIN folder
                    String altLoadDirectory = Path.GetDirectoryName(asm.CodeBase);
                    if (!String.IsNullOrEmpty(altLoadDirectory) && altLoadDirectory.StartsWith(@"file:\"))
                    {
                        altLoadDirectory = altLoadDirectory.Substring(6);
                    }

                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        altLoadDirectory = Path.Combine(altLoadDirectory, subfolder);
                    }

                    if (!Directory.Exists(altLoadDirectory))
                    {
                        if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))
                        {
                            Debug.WriteLine(String.Format("asm.Location is invalid: '{0}'", asm.Location));
                            return(false);
                        }
                        FileInfo      file      = new FileInfo(asm.Location);
                        DirectoryInfo directory = file.Directory;
#if UNITY_EDITOR_WIN
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(
                                    Path.Combine(Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Emgu.CV"), "Plugins"),
                                    subfolder);

                            Debug.WriteLine("Trying unityAltFolder: " + unityAltFolder);
                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                Debug.WriteLine("No suitable directory found to load unmanaged modules");
                                return(false);
                            }
                        }
                        else
#elif (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX)
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(Path.Combine(Path.Combine(
                                                              Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Plugins"),
                                                              "emgucv.bundle"), "Contents"), "MacOS");

                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
#endif
                        {
                            System.Diagnostics.Debug.WriteLine("No suitable directory found to load unmanaged modules");
                            return(false);
                        }
                    }
                    else
                    {
                        loadDirectory = altLoadDirectory;
                    }
                }
#endif
            }

            String oldDir = String.Empty;

            bool addDllDirectorySuccess = false;
            if (!String.IsNullOrEmpty(loadDirectory) && Directory.Exists(loadDirectory))
            {
                if (Platform.ClrType == Platform.Clr.DotNetNative)
                {
                    //do nothing
                }
                else if (Emgu.Util.Platform.OperationSystem == Emgu.Util.Platform.OS.Windows)
                {
                    addDllDirectorySuccess = Emgu.Util.Toolbox.AddDllDirectory(loadDirectory);
                    if (!addDllDirectorySuccess)
                    {
                        System.Diagnostics.Debug.WriteLine(String.Format("Failed to add dll directory: {0}", loadDirectory));
                    }
                }
                else if (Emgu.Util.Platform.OperationSystem == Emgu.Util.Platform.OS.IOS)
                {
                    //do nothing
                    System.Diagnostics.Debug.WriteLine("iOS required static linking, Setting loadDirectory is not supported");
                }
                else
                {
                    oldDir = Environment.CurrentDirectory;
                    Environment.CurrentDirectory = loadDirectory;
                }
            }

            if (addDllDirectorySuccess)
            {
                System.Diagnostics.Debug.WriteLine(
                    String.Format(
                        "Loading Open CV binary for default locations. Current directory: {0}; Additional load folder: {1}",
                        Environment.CurrentDirectory,
                        loadDirectory));
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(
                    String.Format(
                        "Loading Open CV binary for default locations. Current directory: {0}",
                        Environment.CurrentDirectory));
            }
#endif

            bool   success = true;
            string prefix  = string.Empty;
            foreach (String module in unmanagedModules)
            {
                string mName = module;

                //handle special case for universal build
                if (
                    mName.StartsWith("opencv_videoio_ffmpeg") && //opencv_ffmpegvvv(_64).dll
                    (IntPtr.Size == 4)   //32bit application
                    )
                {
                    mName = module.Replace("_64", String.Empty);
                }

                bool optionalComponent = mName.Contains("ffmpeg");

                String fullPath = Path.Combine(prefix, mName);

                //Use absolute path for Windows Desktop
                fullPath = Path.Combine(loadDirectory, fullPath);

                bool fileExist = File.Exists(fullPath);
                bool loaded    = false;

                if (fileExist)
                {
                    //Try to load using the full path
                    System.Diagnostics.Trace.WriteLine(String.Format("Found full path {0} for {1}. Trying to load it.", fullPath, mName));
                    loaded = !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath));
                    if (loaded)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("{0} loaded.", mName));
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("Failed to load {0} from {1}.", mName, fullPath));
                    }
                }
                if (loaded)
                {
                    System.Diagnostics.Trace.WriteLine(String.Format("Trying to load {0} using default path.", mName));
                    loaded = !IntPtr.Zero.Equals(Toolbox.LoadLibrary(mName));
                    if (loaded)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("{0} loaded using default path", mName));
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("Failed to load {0} using default path", mName));
                    }
                }

                if (!loaded)
                {
                    System.Diagnostics.Trace.WriteLine(String.Format("!!! Failed to load {0}.", mName));
                }

                if (!optionalComponent)
                {
                    success &= loaded;
                }
            }

            if (!oldDir.Equals(String.Empty))
            {
                Environment.CurrentDirectory = oldDir;
            }

            return(success);
        }