GetFiles() public static méthode

public static GetFiles ( string path ) : string[]
path string
Résultat string[]
Exemple #1
0
        /// <summary>
        /// Copies the files.
        /// </summary>
        /// <param name="sourceDirectory">Source directory.</param>
        /// <param name="targetDirectory">Target directory.</param>
        /// <param name="criterial">File criteria.</param>
        /// <param name="overrides">if is <strong>true</strong> overrides destination file.</param>
        public static void CopyFiles(string sourceDirectory, string targetDirectory, string criterial, bool overrides)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core.IO, Namespace: iTin.Core.IO, Class: File");
            Logger.Instance.Debug(" Copies specified files from source to target directory");
            Logger.Instance.Debug($" > Signature: (void) CopyFiles({typeof(string)}, {typeof(string)}, {typeof(string)}, {typeof(bool)})");

            SentinelHelper.IsTrue(string.IsNullOrEmpty(sourceDirectory));
            Logger.Instance.Debug($"   > sourceDirectory: {sourceDirectory}");

            SentinelHelper.IsTrue(string.IsNullOrEmpty(targetDirectory));
            Logger.Instance.Debug($"   > targetDirectory: {targetDirectory}");
            Logger.Instance.Debug($"   > criterial: {criterial}");
            Logger.Instance.Debug($"   > overrides: {overrides}");

            string[] items = NativeDirectory.GetFiles(sourceDirectory, criterial, NativeIO.SearchOption.TopDirectoryOnly);
            foreach (var item in items)
            {
                string filename = NativePath.GetFileName(item);
                string target   = NativePath.Combine(targetDirectory, filename);

                NativeFile.Copy(item, target, overrides);
            }

            Logger.Instance.Debug($"  > Output: Has been copied correctly from {sourceDirectory} to {targetDirectory}");
        }
Exemple #2
0
        public List <File> GetFiles(IFileSource.IDirectory current, FileType[] fileTypes, bool recursive)
        {
            Directory currentDir = current as Directory;

            List <File> results = new List <File>();

            if (current != null)
            {
                SearchOption op        = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
                string[]     filePaths = Directories.GetFiles(currentDir.Path, "*.*", op);

                foreach (string filePath in filePaths)
                {
                    File file = new File(filePath, fileTypes);

                    if (file.Type == null)
                    {
                        continue;
                    }

                    results.Add(file);
                }
            }

            return(results);
        }
Exemple #3
0
        /// <summary>
        /// Clean or create temporary work directory.
        /// </summary>
        public static void CleanOrCreateTemporaryDirectory()
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core.IO, Namespace: iTin.Core.IO, Class: File");
            Logger.Instance.Debug(" Clean or create temporary work directory");
            Logger.Instance.Debug(" > Signature: (void) CleanOrCreateTemporaryDirectory()");

            string tempDirectory      = TempDirectoryFullName;
            bool   existTempDirectory = NativeDirectory.Exists(tempDirectory);

            if (existTempDirectory)
            {
                try
                {
                    Array.ForEach(NativeDirectory.GetFiles(tempDirectory), NativeFile.Delete);
                    Logger.Instance.Debug("  > Temporary directory has been cleaned");
                }
                catch (NativeIO.IOException)
                {
                }
            }
            else
            {
                NativeDirectory.CreateDirectory(tempDirectory);
                Logger.Instance.Debug("  > Temporary directory has been created");
            }
        }
        /// <summary>
        /// Просмотр содержимого папки.
        /// </summary>
        /// <returns>Файлы и папки текущего каталога.</returns>
        public string view()
        {
            if (SDirectory.Exists(dname) & dname.Length <= 260)//проверка на существование директории и корректности имени
            {
                try
                {
                    string[] str            = SDirectory.GetDirectories(dname);
                    string[] str1           = SDirectory.GetFiles(dname);
                    string   _directoryShow = string.Empty;
                    string   _filesShow     = string.Empty;
                    foreach (string s in str)
                    {
                        _directoryShow += Path.GetFileName(s) + "\n";
                    }

                    foreach (string s in str1)
                    {
                        _filesShow += Path.GetFileName(s) + "\n";
                    }
                    return("\nПапка просмотра: " + dname + "\nПапки: \n" + _directoryShow + " \nФайлы: \n" + _filesShow); //передача имен директорий и файлов
                }
                catch (Exception e)                                                                                       //обработка исключений для потока
                {
                    LogForOperations("Просмотр содержимого папки", e.Message);                                            //запись ошибки (если есть) в лог
                    throw e;
                }
            }
            LogForOperations("Просмотр содержимого папки", "папка не существует либо содержит в названии более 260 символов"); //запись ошибки в лог, если не выполнилось условие
            return("\nПапка не существует либо содержит в названии более 260 символов.");                                      //передача ошибки
        }
Exemple #5
0
        public List <IFileSource.IEntry> GetFiles(IFileSource.IDirectory current, bool recursive, FileInfoBase[] fileTypes)
        {
            Directory?currentDir = current as Directory;

            List <IFileSource.IEntry> results = new List <IFileSource.IEntry>();

            if (currentDir != null)
            {
                SearchOption op        = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
                string[]     filePaths = Directories.GetFiles(currentDir.Path, "FFXIV_CHARA_*.DAT", op);

                foreach (string filePath in filePaths)
                {
                    File file = new File(this);
                    file.Path = filePath;
                    file.Type = FileService.GetFileInfo <DatCharacterFile>();

                    string fileName   = Paths.GetFileNameWithoutExtension(filePath);
                    string slotNumber = fileName.Substring(12);

                    FileStream stream = new FileStream(filePath, FileMode.Open);
                    stream.Seek(0x30, SeekOrigin.Begin);
                    using BinaryReader reader = new BinaryReader(stream);
                    string desc = Regex.Replace(Encoding.ASCII.GetString(reader.ReadBytes(164)), @"(?![ -~]|\r|\n).", string.Empty);
                    file.Name = slotNumber + ". " + desc.Substring(0, Math.Min(desc.Length, 50));

                    results.Add(file);
                }
            }

            return(results);
        }
        /// <summary>
        /// Информация о папке.
        /// </summary>
        /// <returns>Время создания дирректории, последнего изменения дирректории, последнего обращения к дирректории, уровень доступа к дирректории, размер дирректории, список файлов в дирректории.</returns>
        public string[] info()
        {
            if (SDirectory.Exists(dname) & dname.Length <= 260)//проверка на существование директории и корректности имени
            {
                try
                {
                    List <string> _Info = new List <string>();                                                                         //создание списка, куда будут заноситься сведения
                    _Info.Add(Convert.ToString("\nВремя создания дирректории: " + SDirectory.GetCreationTime(dname)));                 //время создания дирректории
                    _Info.Add(Convert.ToString("\nВремя последнего изменения дирректории: " + SDirectory.GetLastWriteTime(dname)));    //время последнего изменения дирректории
                    _Info.Add(Convert.ToString("\nВремя последнего обращения к дирректории: " + SDirectory.GetLastAccessTime(dname))); //время последнего обращения к дирректории
                    _Info.Add(Convert.ToString("\nУровень доступа к дирректории: " + SDirectory.GetAccessControl(dname)));             //уровень доступа к дирректории
                    _Info.Add(Convert.ToString("\nРазмер дирректории: " + SizeDirrecrory(dname)));                                     //размер дирректории
                    _Info.Add("\nСписок файлов в дирректории: ");                                                                      //список файлов в дирректории
                    string[] file = SDirectory.GetFiles(dname);                                                                        //создание массива строк для имен файлов

                    for (int i = 0; i < file.Length; i++)
                    {
                        _Info.Add("\n" + file[i]);                               //добавление в список имя файла
                    }
                    _Info.Add("\nКонец списка файлов.");                         //объявление о конце операции
                    return(_Info.ToArray());                                     //передача файла
                }
                catch (Exception e)                                              //обработка ислючений для получения информации
                {
                    LogForOperations("Получение информации о папке", e.Message); //запись в лог ошибки (если есть)
                    throw e;
                }
            }
            else
            {
                LogForOperations("Получение информации о файле", "папка не существует либо содержит в названии более 260 символов");//запись ошибки в лог, если условие проверки не выполняется
                return(null);
            }
        }
Exemple #7
0
        /// <summary>
        /// Removes the directory and intermediates files.
        /// </summary>
        public static void DeleteTemporaryOutputFiles()
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core.IO, Namespace: iTin.Core.IO, Class: File");
            Logger.Instance.Debug(" Removes the directory and intermediates files");
            Logger.Instance.Debug(" > Signature: (void) DeleteTemporaryOutputFiles()");

            string tempDirectory = TempDirectoryFullName;

            bool existTempDirectory = NativeDirectory.Exists(tempDirectory);

            if (!existTempDirectory)
            {
                Logger.Instance.Debug("  > Output: Nothing to do, temp directory not exist");
                return;
            }

            try
            {
                Array.ForEach(NativeDirectory.GetFiles(tempDirectory), NativeFile.Delete);
                NativeDirectory.Delete(tempDirectory);
                Logger.Instance.Debug("  > Output: Temp directory has been deleted correctly");
            }
            catch (NativeIO.IOException)
            {
            }
        }
        private static IEnumerable <IOEntry> EnumerateEntriesSafe(string path)
        {
            var foldersLeft = new Queue <string>(64);

            foldersLeft.Enqueue(path);

            while (foldersLeft.Count > 0)
            {
                string   currentFolder = foldersLeft.Dequeue();
                string[] files, folders;

                try{
                    files = DirectoryIO.GetFiles(currentFolder, "*.*", SearchOption.TopDirectoryOnly);
                }catch (Exception) {
                    files = new string[0];
                }

                try{
                    folders = DirectoryIO.GetDirectories(currentFolder, "*.*", SearchOption.TopDirectoryOnly);
                }catch (Exception) {
                    folders = new string[0];
                }

                foreach (string file in files)
                {
                    yield return(new IOEntry(IOEntry.Type.File, file));
                }

                foreach (string folder in folders)
                {
                    foldersLeft.Enqueue(folder);
                    yield return(new IOEntry(IOEntry.Type.Folder, folder));
                }
            }
        }
        Directory ResolveDirectory(Directory directory, IEnumerable<string> children)
        {
            if (!children.Any())
                return directory;

            string childName = children.First();

            Directory info = directory.GetDirectories()
                .Where(x => string.Compare(x.Name.GetName(), childName, true) == 0)
                .SingleOrDefault();

            if (info != null)
            {
                return ResolveDirectory(info, children.Skip(1));
            }

            File file = directory.GetFiles()
                .Where(x => string.Compare(x.Name.GetName(), childName, true) == 0)
                .SingleOrDefault();

            if (file == null)
                throw new InvalidOperationException("Could not get directory: " + childName);

            if (Path.GetExtension(file.Name.GetName()) == ".zip")
            {
                var zipFileDirectory = new ZipFileDirectory(file.Name.Name);
                return ResolveDirectory(zipFileDirectory, children.Skip(1));
            }

            throw new InvalidOperationException("Could not resolve the rest of the path: " + childName);
        }
Exemple #10
0
        public void Prepare()
        {
            var sourceFilesSnapshot = Directory.GetFiles(source);

            foreach (var sourceFile in sourceFilesSnapshot)
            {
                if (Path.GetFileName(sourceFile) == "write.lock")
                {
                    continue; // skip the Lucne lock file
                }
                var destFileName = Path.Combine(tempPath, Path.GetFileName(sourceFile));
                CreateHardLink(
                    destFileName,
                    sourceFile,
                    IntPtr.Zero
                    );

                var fileInfo = new FileInfo(destFileName);
                fileToSize[fileInfo.FullName] = fileInfo.Length;
            }

            // we have to do this outside the main loop because we mustn't
            // do any modification to the DB until we capture the current sizes
            // of all the files
            foreach (var sourceFile in sourceFilesSnapshot)
            {
                Notify("Hard linked " + sourceFile);
            }
        }
        internal Bitmap GetPresentationStoreSlideThumbByIndex(int index)
        {
            logger.Log("Searching presentation thumbnail for index " + index);
            var presentationDir = GetPresentationDir();
            var presentations   = Directory.GetDirectories(presentationDir).OrderBy(f => f);
            int currentOffset   = 0;

            foreach (var presentationUUID in presentations)
            {
                var relativeIndex = index - currentOffset;
                var thumbs        = Directory.GetFiles(presentationUUID, "*.png").OrderBy(f => getIdFromThumbnailName(Path.GetFileNameWithoutExtension(new FileInfo(f).Name)));
                if (thumbs.Count() <= relativeIndex)
                {
                    currentOffset += thumbs.Count();
                    continue;
                }
                var targetThumbFile = thumbs.ElementAt(relativeIndex);
                logger.Log("Using thumbnail " + targetThumbFile);
                using (var image = Image.FromFile(targetThumbFile, true))
                {
                    return(new Bitmap(image));
                }
            }
            throw new ArgumentOutOfRangeException("No such presentation slide index.");
        }
        private void DoReload()
        {
            _reloadPending = false;

            if (Directory == null)
            {
                return;
            }

            _listView.BeginUpdate();

            _updating++;

            string[] selectedFiles = SelectedFiles;

            _listView.Items.Clear();

            if (IODirectory.Exists(Directory))
            {
                foreach (string path in IODirectory.GetFiles(Directory))
                {
                    if (new FileInfo(path).Attributes.IsHidden())
                    {
                        continue;
                    }
                    if (FileBrowserManager == null || !FileBrowserManager.Matches(path))
                    {
                        continue;
                    }

                    var item = new ListViewItem(Path.GetFileNameWithoutExtension(path));
                    item.ImageIndex = _imageList.AddShellIcon(path, ShellIconType.UseFileAttributes);
                    item.Tag        = path;

                    var values = FileBrowserManager.GetValues(path);

                    for (int i = 0; i < values.Length; i++)
                    {
                        item.SubItems.Add(values[i]);
                    }

                    _listView.Items.Add(item);
                }
            }

            foreach (string selectedFile in selectedFiles)
            {
                var item = _listView.Items.Cast <ListViewItem>().SingleOrDefault(p => (string)p.Tag == selectedFile);
                if (item != null)
                {
                    item.Selected = true;
                }
            }

            _updating--;

            _listView.EndUpdate();

            OnSelectedFilesChanged(EventArgs.Empty);
        }
Exemple #13
0
        /// <summary>
        /// Returns a collection that contains all files without extension in a folder with the specified criterial.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="criterial">The criterial.</param>
        /// <param name="timeThreshold">The time threshold.</param>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerable{string}" /> that contains all files in a folder with the specified criterial without extension.
        /// </returns>
        public static IEnumerable <string> GetFilesWithoutExtension(string folder, string criterial, int timeThreshold)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core.IO, Namespace: iTin.Core.IO, Class: File");
            Logger.Instance.Debug(" Returns a collection that contains all files without extension in a folder with the specified criterial");
            Logger.Instance.Debug($" > Signature: ({typeof(IEnumerable<string>)}) GetFilesWithoutExtension({typeof(string)}, {typeof(string)}, {typeof(int)})");
            Logger.Instance.Debug($"   > folder: {folder}");
            Logger.Instance.Debug($"   > criterial: {criterial}");
            Logger.Instance.Debug($"   > timeThreshold: {timeThreshold}");

            Collection <string> files = new Collection <string>();

            Array.ForEach(
                NativeDirectory.GetFiles(folder, criterial, NativeIO.SearchOption.TopDirectoryOnly),
                file =>
            {
                DateTime currentTime   = DateTime.Now;
                DateTime lastWriteTime = NativeFile.GetLastWriteTime(file);
                double diff            = currentTime.Subtract(lastWriteTime).TotalSeconds;
                if (diff >= timeThreshold)
                {
                    files.Add(NativePath.GetFileNameWithoutExtension(file));
                }
            });

            Logger.Instance.Debug($"  > Output: {files.Count} files [{files[0]} ...]");

            return(files);
        }
Exemple #14
0
        /// <summary>
        /// Called to calibrate the data.  Does not actually do anything, other
        /// than display a range report.
        /// </summary>
        public void Calibrate()
        {
            string[] list = Directory.GetFiles(_path);

            _maxDifference = double.NegativeInfinity;
            _minDifference = double.PositiveInfinity;
            _maxPiPs       = int.MinValue;
            _minPiPs       = int.MaxValue;

            foreach (string file in list)
            {
                string fn = FileUtil.GetFileName(new FileInfo(file));
                if (fn.StartsWith("collected") && fn.EndsWith(".csv"))
                {
                    CalibrateFile(file);
                }
            }

            Console.WriteLine(@"Max difference: " + _maxDifference);
            Console.WriteLine(@"Min difference: " + _minDifference);
            Console.WriteLine(@"Max PIPs: " + _maxPiPs);
            Console.WriteLine(@"Min PIPs: " + _minPiPs);
            Console.WriteLine(@"\nSuggested calibration: ");
            Console.WriteLine(@"DIFF_RANGE = " + (int)(Math.Max(_maxDifference, Math.Abs(_minDifference)) * 1.2));
            Console.WriteLine(@"PIP_RANGE = " + (int)(Math.Max(_maxPiPs, Math.Abs(_minPiPs)) * 1.2));
        }
Exemple #15
0
        static void Bundle(bool run = true)
        {
            List <string> files = Directory.GetFiles("../../../Core", "*.dll").ToList();

            files.AddRange(Directory.GetFiles("./", "*.txt"));


            PhysicalFileSystem fileSystem = new PhysicalFileSystem("../../../dev/");

            fileSystem.CreateDirectory(FileSystemPath.Parse("/system/"));

            foreach (string file in files)
            {
                if (!file.Contains("MyOS."))
                {
                    using (Stream fileStream = fileSystem.CreateFile(FileSystemPath.Parse("/system/" + new FileInfo(file).Name.Replace(".dll", ".mye").Replace(".txt", ".ini"))))
                    {
                        byte[] fileBytes = File.ReadAllBytes(file);
                        fileStream.Write(fileBytes, 0, fileBytes.Length);
                    }

                    Console.WriteLine("Written {0}", new FileInfo(file).Name.Replace(".dll", ".mye").Replace(".txt", ".ini"));
                }
            }

            Console.WriteLine("Done");

            if (run)
            {
                //process.Kill();
                //process.Start();
            }
        }
 /// <summary>
 /// Перемещает весь каталог со всем его содержимым в новый каталог либо только файлы из текущего каталога.
 /// </summary>
 /// <param name="NewName">Путь, куда нужно переместить.</param>
 /// <param name="onlyFiles">При значении true — перемещает только файлы текущего каталога.</param>
 public void moveto(string NewName, bool onlyFiles)
 {
     if (!SDirectory.Exists(dname) & dname.Length <= 260 & NewName.Length <= 260)//проверка на существование директории, корректности имени перемещаемой папки и принимающей перемещение
     {
         try
         {
             if (!onlyFiles)
             {
                 SDirectory.Move(dname, NewName); //создание директории
                 dname = NewName;                 //переопределение рабочей папки
             }
             else
             {
                 DirectoryInfo _d = new DirectoryInfo(dname);
                 foreach (string f in SDirectory.GetFiles(dname))
                 {
                     SFile.Move(f, NewName);
                 }
             }
         }
         catch (Exception e)                                   //обработка исключений для перемещения
         {
             LogForOperations("Перемещение папки", e.Message); //запись ошибки (если есть) в лог
             throw e;
         }
     }
     else
     {
         LogForOperations("Перемещение папки", "операция с папкой невозможна, т.к. перемещаемая папка не существует либо в имени больше 260 символов, либо папка с новым именем уже существует");//запись ошибки в лог, если не выполнилась проверка
     }
 }
        private static void InitializeLayoutPreferencesFolder()
        {
            string defaultLayoutPath   = GetDefaultLayoutPath();
            string layoutResourcesPath = Path.Combine(EditorApplication.applicationContentsPath, "Resources/Layouts");

            if (!Directory.Exists(layoutsPreferencesPath))
            {
                Directory.CreateDirectory(layoutsPreferencesPath);
            }

            // Make sure we have a window layouts preferences folder
            if (!Directory.Exists(layoutsDefaultModePreferencesPath))
            {
                // If not copy the standard set of window layouts to the preferences folder
                FileUtil.CopyFileOrDirectory(layoutResourcesPath, layoutsDefaultModePreferencesPath);
                var defaultModeUserLayouts = Directory.GetFiles(layoutsPreferencesPath, "*.wlt");
                foreach (var layoutPath in defaultModeUserLayouts)
                {
                    var fileName = Path.GetFileName(layoutPath);
                    var dst      = Path.Combine(layoutsDefaultModePreferencesPath, fileName);
                    if (!File.Exists(dst))
                    {
                        FileUtil.CopyFileIfExists(layoutPath, dst, false);
                    }
                }
            }

            // Make sure we have the default layout file in the preferences folder
            if (!File.Exists(defaultLayoutPath))
            {
                // If not copy our default file to the preferences folder
                FileUtil.CopyFileOrDirectory(Path.Combine(layoutResourcesPath, kDefaultLayoutName), defaultLayoutPath);
            }
            Debug.Assert(File.Exists(defaultLayoutPath));
        }
Exemple #18
0
        private void folderSelectButton_Click(object sender, EventArgs e)
        {
            var folderResult = folderBrowserDialog1.ShowDialog();

            if (folderResult != DialogResult.OK)
            {
                return;
            }

            dataGridView1.Rows.Clear();

            var files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);

            for (int i = 0; i < files.Length; i++)
            {
                try
                {
                    AddNewImageInfo(files[i]);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    throw;
                }
            }
        }
 public static String[] GetFiles(
     string folder,
     string jobExtension,
     SearchOption searchOption)
 {
     return(MyDirectory.GetFiles(folder, jobExtension, searchOption));
 }
Exemple #20
0
 public void ReadRooms()
 {
     foreach (string file in SystemDirectory.GetFiles(Directory))
     {
         Rooms.Add(RoomManager.Read(Path.GetFileNameWithoutExtension(file)));
     }
 }
Exemple #21
0
        private bool IsIndexingNeeded(DateTime?lastModified)
        {
            var indexFiles = Directory.GetFiles(_indexDirectory).Select(x => new FileInfo(x)).ToList();
            var doIndex    = indexFiles.Any(x => x.LastWriteTimeUtc < lastModified) | !indexFiles.Any();

            return(doIndex | true);//TODO: remove 'true'
        }
Exemple #22
0
        public long Prepare()
        {
            string[] sourceFilesSnapshot;
            try
            {
                sourceFilesSnapshot = Directory.GetFiles(source);
            }
            catch (Exception e)
            {
                logger.WarnException("Could not get directory files, maybe it was deleted", e);
                return(0);
            }
            for (int index = 0; index < sourceFilesSnapshot.Length; index++)
            {
                var sourceFile = sourceFilesSnapshot[index];
                if (Path.GetFileName(sourceFile) == "write.lock")
                {
                    continue; // skip the Lucene lock file
                }
                var destFileName = Path.Combine(tempPath, Path.GetFileName(sourceFile));
                var success      = CreateHardLink(destFileName, sourceFile, IntPtr.Zero);

                if (success == false)
                {
                    // 'The system cannot find the file specified' is explicitly ignored here
                    if (Marshal.GetLastWin32Error() != 2)
                    {
                        throw new Win32Exception();
                    }
                    sourceFilesSnapshot[index] = null;
                    continue;
                }

                try
                {
                    var fileInfo = new FileInfo(destFileName);
                    fileToSize[fileInfo.FullName] = fileInfo.Length;
                }
                catch (IOException)
                {
                    sourceFilesSnapshot[index] = null;
                    // something happened to this file, probably was removed somehow
                }
            }

            // we have to do this outside the main loop because we mustn't
            // do any modification to the DB until we capture the current sizes
            // of all the files
            foreach (var sourceFile in sourceFilesSnapshot)
            {
                if (sourceFile == null)
                {
                    continue;
                }
                Notify("Hard linked " + sourceFile, null, BackupStatus.BackupMessageSeverity.Informational);
            }

            return(fileToSize.Sum(f => f.Value));
        }
        public void ExtractZipShouldExtractZipFile()
        {
            var zipFilePath = CreateZipFile();
            var destination = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            _fileSystem.ExtractZip(zipFilePath, destination);
            Assert.AreEqual(Directory.GetFiles(_directoryPath).Length, Directory.GetFiles(destination).Length);
        }
Exemple #24
0
        /// <summary>
        /// Возвращает содержимое текущего каталога.
        /// </summary>
        public override List <string> view()
        {
            List <string> newList = new List <string>();

            newList.Add(Convert.ToString(ClassDir.GetFiles(dirName)));
            newList.Add(Convert.ToString(ClassDir.GetDirectories(dirName)));
            return(newList);
        }
Exemple #25
0
        public IEnumerable <IGender> Load()
        {
            HashSet <IGender> genders = new HashSet <IGender>();

            string[] files =
                Directory.GetFiles(
                    Directory.GetCurrentDirectory() +
                    GlobalConstants.ASSETS_FOLDER +
                    GlobalConstants.DATA_FOLDER +
                    "/Genders",
                    "*.json",
                    SearchOption.AllDirectories);

            foreach (string file in files)
            {
                JSONParseResult result = JSON.Parse(File.ReadAllText(file));

                if (result.Error != Error.Ok)
                {
                    this.ValueExtractor.PrintFileParsingError(result, file);
                    continue;
                }

                if (!(result.Result is Dictionary dictionary))
                {
                    GlobalConstants.ActionLog.Log("Could not parse JSON in " + file + " into a Dictionary.", LogLevel.Warning);
                    continue;
                }

                ICollection <Dictionary> gendersCollection =
                    this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(dictionary, "Genders");

                foreach (Dictionary gender in gendersCollection)
                {
                    string name             = this.ValueExtractor.GetValueFromDictionary <string>(gender, "Name");
                    string possessive       = this.ValueExtractor.GetValueFromDictionary <string>(gender, "Possessive");
                    string personalSubject  = this.ValueExtractor.GetValueFromDictionary <string>(gender, "PersonalSubject");
                    string personalObject   = this.ValueExtractor.GetValueFromDictionary <string>(gender, "PersonalObject");
                    string reflexive        = this.ValueExtractor.GetValueFromDictionary <string>(gender, "Reflexive");
                    string possessivePlural = this.ValueExtractor.GetValueFromDictionary <string>(gender, "PossessivePlural");
                    string reflexivePlural  = this.ValueExtractor.GetValueFromDictionary <string>(gender, "ReflexivePlural");
                    string isOrAre          = this.ValueExtractor.GetValueFromDictionary <string>(gender, "IsOrAre");

                    genders.Add(new BaseGender(
                                    name,
                                    possessive,
                                    personalSubject,
                                    personalObject,
                                    reflexive,
                                    possessivePlural,
                                    reflexivePlural,
                                    isOrAre));
                }
            }

            return(genders);
        }
        internal string GetPersistedTheme()
        {
            var themes = Directory.GetFiles(GetPersistenceDir(), "*" + THEME_EXTENSION,
                                            System.IO.SearchOption.TopDirectoryOnly);

            if (themes.Length > 0)
            {
                return(themes[0]);
            }
            return(null);
        }
Exemple #27
0
        private static string GetBundle(string appFolder)
        {
            var bundleFile = Directory.GetFiles(appFolder, "*.msixbundle").FirstOrDefault();

            if (!File.Exists(bundleFile))
            {
                Console.WriteLine("找不到 msixbundle 安装文件");
            }

            return(bundleFile);
        }
Exemple #28
0
        private static string GetCerFile(string appFolder)
        {
            var cerFile = Directory.GetFiles(appFolder, "*.cer").FirstOrDefault();

            if (!File.Exists(cerFile))
            {
                Console.WriteLine("找不到 cer 证书文件");
            }

            return(cerFile);
        }
Exemple #29
0
        protected void LoadDefinitions()
        {
            string[] files = Directory.GetFiles(
                Directory.GetCurrentDirectory() +
                GlobalConstants.ASSETS_FOLDER +
                GlobalConstants.DATA_FOLDER +
                "Sprite Definitions/GUI/",
                "*.json",
                SearchOption.AllDirectories);

            foreach (string file in files)
            {
                if (File.Exists(file) == false)
                {
                    GlobalConstants.ActionLog.Log("Could not find GUI definitions file " + file, LogLevel.Warning);
                    return;
                }

                JSONParseResult result = JSON.Parse(File.ReadAllText(file));

                if (result.Error != Error.Ok)
                {
                    this.ValueExtractor.PrintFileParsingError(result, file);
                }

                if (!(result.Result is Dictionary dictionary))
                {
                    GlobalConstants.ActionLog.Log("Could not parse JSON to Dictionary from " + file, LogLevel.Warning);
                    return;
                }

                string tileSetName = this.ValueExtractor.GetValueFromDictionary <string>(
                    this.ValueExtractor.GetValueFromDictionary <Dictionary>(dictionary, "TileSet"),
                    "Name");

                var spriteData = GlobalConstants.GameManager.ObjectIconHandler.GetTileSet(tileSetName);
                foreach (SpriteData data in spriteData)
                {
                    if (this.Themes.ContainsKey(data.m_Name) == false)
                    {
                        Theme theme = new Theme();
                        theme.SetIcon(data.m_Name, "ManagedUIElement", data.m_Parts.First().m_FrameSprite.GetFrame("default", 0));
                        this.Themes.Add(data.m_Name, theme);
                    }

                    if (this.UISprites.ContainsKey(data.m_Name))
                    {
                        continue;
                    }

                    this.UISprites.Add(data.m_Name, new SpriteState(data.m_Name, data));
                }
            }
        }
Exemple #30
0
        public IResourceProvider AddRoot(string RootDir)
        {
            string[] VPKs = IODirectory.GetFiles(RootDir, "*_dir.vpk", SearchOption.AllDirectories);

            foreach (var VPK in VPKs)
            {
                Add(VPK);
            }

            return(this);
        }
Exemple #31
0
 public static string FindSettingsFileInFolder(string folderPath)
 {
     try
     {
         return(Directory.GetFiles(folderPath, "*.bloomCollection").First());
     }
     catch (Exception)
     {
         throw new ApplicationException(string.Format("Bloom expected to find a .bloomCollectionFile in {0}, but there isn't one.", folderPath));
     }
 }
        public async Task SyncDirectory(Directory dir, string parentId)
        {
            // Get directories of parent and find this folder's id in drive (if exists)
            IList<DriveFile> parentChildren = mDMgr.FetchChildrenDirectories(parentId);

            string dirId = "";
            foreach (DriveFile file in parentChildren)
                if (file.Title.Equals(dir.GetName()))
                    dirId = file.Id;

            // Folder does not exist so create it
            if (dirId.Equals(""))
                dirId = mDMgr.CreateDirectory(dir.GetName(), dir.GetName(), parentId).Id;

            // Get files and folders of this directory in drive
            IList<DriveFile> children = mDMgr.FetchChildren(dirId);

            // Start syncing this directory
            // Check the drive for any files and folders that do not exist locally and delete them
            List<DriveFile> foldersToDelete = new List<DriveFile>();
            foreach (DriveFile dFile in children)
            {
                bool existsLocally = false;

                foreach (string file in dir.GetFiles())
                {
                    if (dFile.Title.Equals(Path.GetFileName(file)))
                    {
                        existsLocally = true;
                        break;
                    }
                }

                foreach (Directory subdir in dir.getSubDirectories())
                {
                    if(dFile.Title.Equals(subdir.GetName()))
                    {
                        existsLocally = true;
                        break;
                    }
                }

                // Delete if it doesn't exist
                if (!existsLocally)
                {
                    string type;
                    if (DriveManager.IsDirectory(dFile))
                        type = "directory";
                    else
                        type = "file";

                    Console.WriteLine("Deleting " + type + ": " + dFile.Title);
                    mDMgr.DeleteFile(dFile.Id);
                }
            }

            IList<DriveFile> childrenFiles = children.Where(d => !(DriveManager.IsDirectory(d))).ToList();
            // Upload or update files
            foreach (string file in dir.GetFiles())
            {
                // Get simple filename
                string filename = Path.GetFileName(file);

                // Try to find it on drive
                DriveFile fileInDrive = null;
                foreach (DriveFile dFile in childrenFiles)
                {
                    if (dFile.Title.Equals(filename))
                    {
                        fileInDrive = dFile;
                        break;
                    }
                }

                // If didn't found it, upload it, else update it
                if (fileInDrive != null)
                {
                    // If the local file is modified since the last time it was uploaded on drive, update it.
                    // If not, just leave it as it is. In case of error (eg. the fileInDrive.ModifiedDate is null)
                    // just upload it anyway. Better be safe than sorry :)
                    bool shouldUpload = true;
                    if (fileInDrive.ModifiedDate.HasValue)
                    {
                        DateTime localDate = System.IO.File.GetLastWriteTime(file);
                        DateTime driveDate = (DateTime)fileInDrive.ModifiedDate;

                        if (DateTime.Compare(localDate, driveDate) <= 0)
                            shouldUpload = false;
                    }

                    if (shouldUpload)
                    {
                        mUploader.SetupFile(file, file, dirId);
                        await mUploader.Update();
                    }
                    else
                    {
                        Console.WriteLine("Skipped -- " + file);
                    }
                }
                else
                {
                    mUploader.SetupFile(file, file, dirId);
                    await mUploader.Upload();
                }
            }

            // Now get subdirectories and sync them
            foreach (Directory subDir in dir.getSubDirectories())
                await SyncDirectory(subDir, dirId);
        }
        File ResolveFile(Directory directoryInfo, IEnumerable<string> children)
        {
            if (!children.Any())
                throw new InvalidOperationException("Unable to resolve file: " + directoryInfo.Name);

            string childName = children.First();

            Directory info = directoryInfo.GetDirectories()
                .Where(x => string.Compare(x.Name.GetName(), childName, true) == 0)
                .SingleOrDefault();

            if (info != null)
            {
                return ResolveFile(info, children.Skip(1));
            }

            File file = directoryInfo.GetFiles()
                .Where(x => string.Compare(x.Name.GetName(), childName, true) == 0)
                .SingleOrDefault();

            if (file == null)
                throw new InvalidOperationException("Could not get file: " + childName);

            if (!children.Skip(1).Any())
                return file;

            //			if (Path.GetExtension(file.Name.GetName()) == ".zip")
            //			{
            //				var zipFileDirectory = new ZipFileDirectory(file.Name.Name);
            //				return ResolveFile(zipFileDirectory, children.Skip(1));
            //			}

            throw new NotImplementedException();
        }