System.IO.Directory.GetFiles(string, string, System.IO.SearchOption)

Here are the examples of the csharp api System.IO.Directory.GetFiles(string, string, System.IO.SearchOption) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2430 Examples 7

19 View Source File : IrdProvider.cs
License : MIT License
Project Creator : 13xforever

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            ProductCode = ProductCode?.ToUpperInvariant();
            var result = new HashSet<DiscKeyInfo>();
            var knownFilenames = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
            Log.Trace("Searching local cache for a match...");
            if (Directory.Exists(discKeyCachePath))
            {
                var matchingIrdFiles = Directory.GetFiles(discKeyCachePath, "*.ird", SearchOption.TopDirectoryOnly);
                foreach (var irdFile in matchingIrdFiles)
                {
                    try
                    {
                        try
                        {
                            var ird = IrdParser.Parse(File.ReadAllBytes(irdFile));
                            result.Add(new DiscKeyInfo(ird.Data1, null, irdFile, KeyType.Ird, ird.Crc32.ToString("x8")));
                            knownFilenames.Add(Path.GetFileName(irdFile));
                        }
                        catch (InvalidDataException)
                        {
                            File.Delete(irdFile);
                            continue;
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e);
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn(e, e.Message);
                    }
                }
            }

            Log.Trace("Searching IRD Library for match...");
            var irdInfoList = await Client.SearchAsync(ProductCode, cancellationToken).ConfigureAwait(false);
            var irdList = irdInfoList?.Data?.Where(
                              i => !knownFilenames.Contains(i.Filename) && i.Filename.Substring(0, 9).ToUpperInvariant() == ProductCode
                          ).ToList() ?? new List<SearchResulreplacedem>(0);
            if (irdList.Count == 0)
                Log.Debug("No matching IRD file was found in the Library");
            else
            {
                Log.Info($"Found {irdList.Count} new match{(irdList.Count == 1 ? "" : "es")} in the IRD Library");
                foreach (var irdInfo in irdList)
                {
                    var ird = await Client.DownloadAsync(irdInfo, discKeyCachePath, cancellationToken).ConfigureAwait(false);
                    result.Add(new DiscKeyInfo(ird.Data1, null, Path.Combine(discKeyCachePath, irdInfo.Filename), KeyType.Ird, ird.Crc32.ToString("x8")));
                    knownFilenames.Add(irdInfo.Filename);
                }
            }
            if (knownFilenames.Count == 0)
            {
                Log.Warn("No valid matching IRD file could be found");
                Log.Info($"If you have matching IRD file, you can put it in '{discKeyCachePath}' and try dumping the disc again");
            }

            Log.Info($"Found {result.Count} IRD files");
            return result;
        }

19 View Source File : RedumpProvider.cs
License : MIT License
Project Creator : 13xforever

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            var result = new HashSet<DiscKeyInfo>();
            try
            {
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
                if (embeddedResources.Any())
                    Log.Trace("Loading embedded redump keys");
                else
                    Log.Warn("No embedded redump keys found");
                foreach (var res in embeddedResources)
                {
                    using var resStream = replacedembly.GetManifestResourceStream(res);
                    using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
                    foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
                                                                    || e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        using var keyStream = zipEntry.Open();
                        using var memStream = new MemoryStream();
                        await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
                        var discKey = memStream.ToArray();
                        if (zipEntry.Length > 256/8*2)
                        {
                            Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
                            continue;
                        }
                        if (discKey.Length > 16)
                        {
                            discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                        }

                        try
                        {
                            result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, $"Invalid disc key format: {discKey}");
                        }
                    }
                }
                if (result.Any())
                    Log.Info($"Found {result.Count} embedded redump keys");
                else
                    Log.Warn($"Failed to load any embedded redump keys");
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to load embedded redump keys");
            }

            Log.Trace("Loading cached redump keys");
            var diff = result.Count;
            try
            {
                if (Directory.Exists(discKeyCachePath))
                {
                    var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
                    foreach (var dkeyFile in matchingDiskKeys)
                    {
                        try
                        {
                            try
                            {
                                var discKey = File.ReadAllBytes(dkeyFile);
                                if (discKey.Length > 16)
                                {
                                    try
                                    {
                                        discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
                                    }
                                }
                                result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
                            }
                            catch (InvalidDataException)
                            {
                                File.Delete(dkeyFile);
                                continue;
                            }
                            catch (Exception e)
                            {
                                Log.Warn(e);
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, e.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, "Failed to load redump keys from local cache");
            }
            diff = result.Count - diff;
            Log.Info($"Found {diff} cached disc keys");
            return result;
        }

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public void Load(string path, string pattern, SearchOption options)
        {
            var files = System.IO.Directory.GetFiles(path, pattern, options);
            foreach (var item in files)
            {
                Load(item);
            }
        }

19 View Source File : TestSite.cs
License : MIT License
Project Creator : 188867052

public IList<RouteInfo> GetAllRouteInfo()
        {
            var dllFile = Directory.GetFiles(Environment.CurrentDirectory, $"{this.projectName}.dll", SearchOption.AllDirectories).FirstOrDefault();
            if (string.IsNullOrEmpty(dllFile))
            {
                throw new ArgumentException($"No {this.projectName}.dll file found under the directory: {Environment.CurrentDirectory}.");
            }

            Console.WriteLine($"the project name:{this.projectName}.");
            Console.WriteLine($"find dll file:{dllFile}.");

            replacedembly replacedembly = replacedembly.LoadFile(dllFile);
            Type type = replacedembly.GetTypes().FirstOrDefault(o => o.Name == "Startup");

            if (type == null)
            {
                throw new ArgumentException($"No Startup.cs clreplaced found under the dll file: {dllFile}.");
            }

            var builder = new WebHostBuilder()
                .UseEnvironment("Development")
                .UseContentRoot(AppContext.BaseDirectory)
                .UseStartup(type);

            TestServer server = new TestServer(builder);
            IRoutereplacedyzer services = (IRoutereplacedyzer)server.Host.Services.GetService(typeof(IRoutereplacedyzer));
            var client = server.CreateClient();
            return services.GetAllRouteInfo();
        }

19 View Source File : GenerateCommand.cs
License : MIT License
Project Creator : 188867052

private int Initialize()
        {
            try
            {
                CommondConfig config = new CommondConfig();

                // From console.
                if (!string.IsNullOrEmpty(this.ProjectName))
                {
                    string fileFullPath = Directory.GetFiles(".", $"{this.ProjectName}.csproj", SearchOption.AllDirectories).FirstOrDefault();
                    if (string.IsNullOrEmpty(fileFullPath))
                    {
                        System.Console.Write($"Project {this.ProjectName} is not exist.");
                        return 1;
                    }

                    config.ProjectPath = new FileInfo(fileFullPath).DirectoryName;
                    config.ProjectName = this.ProjectName;
                    config.GenerateMethod = this.GenerateMethod == "1" || this.GenerateMethod.Equals("true", StringComparison.InvariantCultureIgnoreCase);
                }
                else
                {
                    // From appsettings.json.
                    this.ConfigJsonPath = Directory.GetFiles(".", "appsettings.json", SearchOption.AllDirectories).FirstOrDefault();
                    if (string.IsNullOrEmpty(this.ConfigJsonPath))
                    {
                        this.Console.WriteLine("No appsettings.json file found, will generate code with default setting.");
                    }

                    string appSettings = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(this.ConfigJsonPath)).RouteGenerator.ToString();
                    config = JsonConvert.DeserializeObject<CommondConfig>(appSettings);
                    if (string.IsNullOrEmpty(config.ProjectName))
                    {
                        System.Console.Write($"Please provide ProjectName.");
                        return 1;
                    }

                    string fileFullPath = Directory.GetFiles(".", $"{config.ProjectName}.csproj", SearchOption.AllDirectories).FirstOrDefault();
                    if (string.IsNullOrEmpty(fileFullPath))
                    {
                        System.Console.Write($"Project {config.ProjectName} is not exist.");
                        return 1;
                    }

                    config.ProjectPath = new FileInfo(fileFullPath).DirectoryName;
                }

                this.Config = config;
                this.Console.WriteLine(JsonConvert.SerializeObject(config, Formatting.Indented));

                if (string.IsNullOrEmpty(this.Config.OutPutFile))
                {
                    this.Config.OutPutFile = "Routes.Generated.cs";
                }

                if (!this.Config.OutPutFile.EndsWith(".cs"))
                {
                    this.Config.OutPutFile += ".cs";
                }

                if (string.IsNullOrEmpty(this.Config.ProjectName))
                {
                    this.Console.WriteLine($"Please provide ProjectName.");
                    return 1;
                }
            }
            catch (Exception ex)
            {
                this.Console.WriteLine("Read config file error.");
                this.Console.WriteLine(ex.Message);
                this.Console.WriteLine(ex.StackTrace);
                return 1;
            }

            return 0;
        }

19 View Source File : RouteGeneratorTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public void TestApiRouteGenerator()
        {
            try
            {
                var routeInfos = new TestSite(nameof(Api)).GetAllRouteInfo();
                var json = JsonConvert.SerializeObject(routeInfos, Formatting.Indented);
                Console.WriteLine(json);
                DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory);

                var file = Directory.GetFiles(di.Parent.Parent.Parent.Parent.FullName, "json.json", SearchOption.AllDirectories).FirstOrDefault();
                File.WriteAllText(file, json);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2401dem

public static int Denoise()
        {
            if (_is_folder)
            {
                if (Directory.Exists(_input_path) || Directory.Exists(_input_path.Substring(0, _input_path.LastIndexOf('\\') > 0 ? _input_path.LastIndexOf('\\') : 0)))
                {
                    if (Directory.Exists(_output_path) || Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\') > 0 ? _output_path.LastIndexOf('\\') : 0)))
                    {
                        var file_paths = Directory.GetFiles(_input_path, "*.*", SearchOption.TopDirectoryOnly);
                        List<string> input_file_paths = new List<string>();
                        List<string> output_file_paths = new List<string>();
                        foreach (string file_path in file_paths)
                        {
                            Regex regex = new Regex(".\\.(bmp|jpg|png|tif|exr)$", RegexOptions.IgnoreCase);
                            if (regex.IsMatch(file_path))
                            {
                                input_file_paths.Add(file_path);
                                output_file_paths.Add(_output_path + "\\out_" + file_path.Substring(file_path.LastIndexOf('\\') + 1));
                                Console.WriteLine(file_path);
                            }
                        }
                        int width = _getWidth(input_file_paths[0].ToCharArray());
                        int height = _getHeight(input_file_paths[0].ToCharArray());

                        if (width == -1 || height == -1)
                        {
                            MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Program.form1.unlockButton();
                            return -1;
                        }
                        //Bitmap pBuffer = new Bitmap(input_file_paths[0], false);
                        IntPtr tmpptr = new IntPtr();

                        _jobStart(width, height, _blend);
                        for (int i = 0; i < input_file_paths.Count; ++i)
                        {
                            Program.form1.SetProgress((float)i / (float)input_file_paths.Count);
                            if (File.Exists(output_file_paths[i]))
                                continue;
                            //IntPtr tmpptr = 
                            tmpptr = _denoiseImplement(input_file_paths[i].ToCharArray(), output_file_paths[i].ToCharArray(), _blend, _is_folder);
                            /*if (tmpptr != null)
                                if (Program.form1.DrawToPictureBox(tmpptr, pBuffer.Width, pBuffer.Height) == 0)
                                    continue;
                                else
                                {
                                    MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    break;
                                }
                            else
                            {
                                //MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                //break;
                            }*/
                        }

                        _jobComplete();
                        if (tmpptr != null)
                            if (Program.form1.DrawToPictureBox(tmpptr, width, height) != 0)
                                MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        Program.form1.SetProgress(1.0f);
                        Program.form1.unlockButton();
                        return 0;
                    }
                    else
                        MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("Input folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (File.Exists(_input_path))
                {
                    if (Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\'))))
                    {
                        int width = _getWidth(_input_path.ToCharArray());
                        int height = _getHeight(_input_path.ToCharArray());
                        Console.WriteLine(width.ToString());
                        Console.WriteLine(height.ToString());
                        if (width == -1 || height == -1)
                        {
                            MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Program.form1.unlockButton();
                            return -1;
                        }

                        _jobStart(width, height, _blend);
                        IntPtr tmpptr = _denoiseImplement(_input_path.ToCharArray(), _output_path.ToCharArray(), _blend, _is_folder);
                        if (tmpptr != null)
                        {
                            if (Program.form1.DrawToPictureBox(tmpptr, width, height) == -1)
                                MessageBox.Show("Picture Size Error(NULL to Draw)!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                            MessageBox.Show("Picture Size Error!(NULL Return)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Program.form1.SetProgress(1.0f);
                        Program.form1.unlockButton();
                        _jobComplete();
                        return 0;
                    }
                    else
                        MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("Input file does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Program.form1.unlockButton();
            return -1;
        }

19 View Source File : CustomMusicManager.cs
License : MIT License
Project Creator : 39M

void InitMusicGroup()
    {
        musicUIItemList = new List<CustomMusicUIItem>();

        string[] fileList = Directory.GetFiles(Application.streamingreplacedetsPath, "*.mp3");

        Debug.Log(string.Format("{0} files found.", fileList.Length));

        foreach (var filePath in fileList)
        {
            Debug.Log("Found music: " + filePath);

            string fileName = filePath.Substring(filePath.LastIndexOf(@"\") + 1);
            CustomMusicUIItem item = CreateMusicUIItem(fileName);
            musicUIItemList.Add(item);
        }
    }

19 View Source File : LinkUtil.cs
License : MIT License
Project Creator : 404Lcc

public static void BuildLink()
        {
            List<replacedembly> replacedemblieList = new List<replacedembly>();
            replacedemblieList.Add(typeof(Object).replacedembly);
            replacedemblieList.Add(typeof(UnityEngine.Object).replacedembly);
            replacedemblieList.Add(typeof(Transform).replacedembly);
            replacedemblieList.Add(typeof(GameObject).replacedembly);
            replacedemblieList.Add(typeof(Image).replacedembly);
            replacedemblieList.Add(typeof(Init).replacedembly);
            string[] filePaths = Directory.GetFiles("replacedets", "*.dll", SearchOption.AllDirectories);
            foreach (string item in filePaths)
            {
                if (item.ToLower().Contains("editor") || item.ToLower().Contains("plugins"))
                {
                    continue;
                }
                replacedemblieList.Add(replacedembly.LoadFrom(item));
            }
            replacedemblieList = replacedemblieList.Distinct().ToList();
            XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
            XmlElement linkerElement = xmlDoreplacedent.CreateElement("linker");
            foreach (replacedembly item in replacedemblieList)
            {
                XmlElement replacedemblyElement = xmlDoreplacedent.CreateElement("replacedembly");
                replacedemblyElement.SetAttribute("fullname", item.GetName().Name);
                foreach (Type typeItem in item.GetTypes())
                {
                    if (typeItem.FullName == "Win32")
                    {
                        continue;
                    }
                    XmlElement typeElement = xmlDoreplacedent.CreateElement("type");
                    typeElement.SetAttribute("fullname", typeItem.FullName);
                    typeElement.SetAttribute("preserve", "all");
                    //增加子节点
                    replacedemblyElement.AppendChild(typeElement);
                }
                linkerElement.AppendChild(replacedemblyElement);
            }
            xmlDoreplacedent.AppendChild(linkerElement);
            string path = "replacedets/link.xml";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            xmlDoreplacedent.Save(path);
        }

19 View Source File : LccViewEditor.cs
License : MIT License
Project Creator : 404Lcc

public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            LccView lccView = (LccView)target;
            if (GUILayout.Button(lccView.clreplacedName))
            {
                string directoryName = string.Empty;
                switch (Path.GetFileNameWithoutExtension(lccView.type.GetType().replacedembly.ManifestModule.Name))
                {
                    case "Unity.Model":
                        directoryName = "Scripts";
                        break;
                    case "Unity.Hotfix":
                        directoryName = "Hotfix";
                        break;
                    case "ILRuntime":
                        directoryName = "Hotfix";
                        break;
                }
                string fileName = lccView.clreplacedName;
                string[] filePaths = Directory.GetFiles($"replacedets/{directoryName}", "*.cs", SearchOption.AllDirectories);
                foreach (string item in filePaths)
                {
                    if (item.Substring(item.LastIndexOf(@"\") + 1) == $"{fileName}.cs")
                    {
                        EditorGUIUtility.PingObject(replacedetDatabase.LoadreplacedetAtPath<Textreplacedet>(item));
                        replacedetDatabase.Openreplacedet(replacedetDatabase.LoadreplacedetAtPath<Object>(item), 0);
                    }
                }
            }
            ObjectTypeUtil.Draw(lccView.type, 0);
        }

19 View Source File : UwpAppxBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static string GetManifestFilePath(IBuildInfo buildInfo)
        {
            var fullPathOutputDirectory = Path.GetFullPath(buildInfo.OutputDirectory);
            Debug.Log($"Searching for appx manifest in {fullPathOutputDirectory}...");

            // Find the manifest, replacedume the one we want is the first one
            string[] manifests = Directory.GetFiles(fullPathOutputDirectory, "Package.appxmanifest", SearchOption.AllDirectories);

            if (manifests.Length == 0)
            {
                Debug.LogError($"Unable to find Package.appxmanifest file for build (in path - {fullPathOutputDirectory})");
                return null;
            }

            if (manifests.Length > 1)
            {
                Debug.LogWarning("Found more than one appxmanifest in the target build folder!");
            }

            return manifests[0];
        }

19 View Source File : UwpAppxBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static string GetreplacedemblyCSharpProjectFilePath(IBuildInfo buildInfo)
        {
            var fullPathOutputDirectory = Path.GetFullPath(buildInfo.OutputDirectory);
            Debug.Log($"Searching for 'replacedembly-CSharp.csproj' in {fullPathOutputDirectory}...");

            // Find the manifest, replacedume the one we want is the first one
            string[] manifests = Directory.GetFiles(fullPathOutputDirectory, "replacedembly-CSharp.csproj", SearchOption.AllDirectories);

            if (manifests.Length == 0)
            {
                Debug.LogError($"Unable to find 'replacedembly-CSharp.csproj' file for build (in path - {fullPathOutputDirectory})");
                return null;
            }

            if (manifests.Length > 1)
            {
                Debug.LogWarning("Found more than one 'replacedembly-CSharp.csproj' in the target build folder!");
            }

            return manifests[0];
        }

19 View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static void SearchForFolders(string rootPath, CancellationToken ct)
        {
            try
            {
                var filePathResults = Directory.GetFiles(rootPath, SentinelFilePattern, SearchOption.AllDirectories);
                foreach (var sentinelFilePath in filePathResults)
                {
                    TryRegisterModuleViaFile(sentinelFilePath);

                    if (ct.IsCancellationRequested)
                    {
                        ct.ThrowIfCancellationRequested();
                    }
                }

                // Create the Generated folder, if the user tries to delete the Generated folder it will be created again
                TryToCreateGeneratedFolder();
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine($"\n{nameof(OperationCanceledException)} thrown\n");
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
            }
        }

19 View Source File : OVRDirectorySyncer.cs
License : MIT License
Project Creator : absurd-joy

private HashSet<string> RelevantRelativeFilesBeneathDirectory(string path, CancellationToken cancellationToken)
	{
		return new HashSet<string>(Directory.GetFiles(path, "*", SearchOption.AllDirectories)
			.TakeWhile((s) => !cancellationToken.IsCancellationRequested)
			.Select(p => PathHelper.MakeRelativePath(path, p)).Where(RelativeFilePathIsRelevant));
	}

19 View Source File : ShellUpgradeTask.cs
License : MIT License
Project Creator : Accelerider

protected override async void OnDownloadCompleted(UpgradeInfo info)
        {
            base.OnDownloadCompleted(info);

            if (info.Version <= CurrentVersion) return;

            var launcherPath = Directory
                .GetFiles(GetInstallPath(info.Version))
                .SingleOrDefault(item => Path.GetFileName(item) == ProcessController.LauncherName);

            if (!string.IsNullOrEmpty(launcherPath))
            {
                try
                {
                    if (File.Exists(ProcessController.LauncherPath))
                    {
                        File.Delete(ProcessController.LauncherPath);
                    }
                    File.Move(launcherPath, ProcessController.LauncherPath);
                }
                catch (Exception e)
                {
                    Logger.Error($"[MOVE FILE] Move the {ProcessController.LauncherName} file failed. ", e);
                }
            }

            await ShowUpgradeNotificationDialogAsync(info);
        }

19 View Source File : RemoteModuleTypeLoader.cs
License : MIT License
Project Creator : Accelerider

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is rethrown as part of a completion event")]
        public async void LoadModuleType(IModuleInfo moduleInfo)
        {
            if (moduleInfo == null)
                throw new ArgumentNullException(nameof(moduleInfo));

            if (!(moduleInfo is AppInfo app))
                throw new ArgumentException($"the moduleInfo argument must be {nameof(AppInfo)} type. ");

            try
            {
                var targetPath = Path.Combine(AcceleriderFolders.Apps, $"{app.ModuleName}-{app.Version.ToString(3)}");

                if (!Directory.Exists(targetPath))
                {
                    await DownloadModuleAsync(app, targetPath);
                }

                // 3. Load dll
                Directory
                    .GetFiles(targetPath, "*.dll", SearchOption.AllDirectories)
                    .ForEach(item => _replacedemblyResolver.LoadreplacedemblyFrom(item));

                // 4. Notify
                RaiseLoadModuleCompleted(moduleInfo, null);
            }
            catch (Exception ex)
            {
                RaiseLoadModuleCompleted(moduleInfo, ex);
            }
        }

19 View Source File : GDLELoader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool TryLoadLandblocksInParallel(string folder, out List<Models.Landblock> results)
        {
            try
            {
                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories);

                var landblocks = new ConcurrentBag<Models.Landblock>();

                Parallel.ForEach(files, file =>
                {
                    if (TryLoadLandblock(file, out var result))
                        landblocks.Add(result);
                });

                results = new List<Models.Landblock>(landblocks);

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 View Source File : GDLELoader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool TryLoadRecipeCombinedInParallel(string folder, out List<Models.RecipeCombined> results)
        {
            try
            {
                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories);

                var recipes = new ConcurrentBag<Models.RecipeCombined>();

                Parallel.ForEach(files, file =>
                {
                    if (TryLoadRecipeCombined(file, out var result))
                        recipes.Add(result);
                });

                results = new List<Models.RecipeCombined>(recipes);

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 View Source File : LifestonedLoader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool TryLoadWeenies(string folder, out List<global::Lifestoned.DataModel.Gdle.Weenie> results)
        {
            try
            {
                results = new List<global::Lifestoned.DataModel.Gdle.Weenie>();

                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories).OrderByDescending(f => new FileInfo(f).CreationTime).ToList();

                foreach (var file in files)
                {
                    if (TryLoadWeenie(file, out var result))
                        results.Add(result);
                }

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 View Source File : LifestonedLoader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool TryLoadWeeniesInParallel(string folder, out List<global::Lifestoned.DataModel.Gdle.Weenie> results)
        {
            try
            {
                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories);

                var weenies = new ConcurrentBag<global::Lifestoned.DataModel.Gdle.Weenie>();

                Parallel.ForEach(files, file =>
                {
                    if (TryLoadWeenie(file, out var result))
                        weenies.Add(result);
                });

                results = new List<global::Lifestoned.DataModel.Gdle.Weenie>(weenies);

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 View Source File : LifestonedLoader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool TryLoadWeeniesConverted(string folder, out List<Weenie> results, bool correctForEnumShift = false)
        {
            try
            {
                results = new List<Weenie>();

                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories).OrderByDescending(f => new FileInfo(f).CreationTime).ToList();

                foreach (var file in files)
                {
                    if (TryLoadWeenieConverted(file, out var result, correctForEnumShift))
                        results.Add(result);
                }

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 View Source File : LifestonedLoader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool TryLoadWeeniesConvertedInParallel(string folder, out List<Weenie> results, bool correctForEnumShift = false)
        {
            try
            {
                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories);

                var weenies = new ConcurrentBag<Weenie>();

                Parallel.ForEach(files, file =>
                {
                    if (TryLoadWeenieConverted(file, out var result, correctForEnumShift))
                        weenies.Add(result);
                });

                results = new List<Weenie>(weenies);

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 View Source File : ProjectRootFolder.cs
License : MIT License
Project Creator : action-bi-toolkit

public void Dispose()
        {
            // Do not delete anything if an unhandled error has occurred
            if (!_committed) return;

            if (_filesWritten.Count == 0)
            {
                if (Directory.Exists(BasePath))
                {
                    Directory.Delete(BasePath, recursive: true);
                    Log.Information("No files written. Removed base folder: {Path}", BasePath);
                }

                return;
            }

            // Remove any existing files that have not been updated
            foreach (var path in Directory.GetFiles(BasePath, "*.*", SearchOption.AllDirectories))
            {
                if (!_filesWritten.Contains(path))
                {
                    File.Delete(path);
                    Log.Information("Removed file: {Path}", path);
                }
            }

            // Remove empty dirs:
            foreach (var dir in Directory.GetDirectories(BasePath, "*", SearchOption.AllDirectories).ToArray())
            {
                if (Directory.Exists(dir) && Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories).FirstOrDefault() == null)
                {
                    Directory.Delete(dir, recursive: true); // Could be root of a series of empty folders
                    Log.Information("Removed empty directory: {Path}", dir);
                }
            }

            // TODO Check if nested empty dirs need to be removed explicitly
            // ./ROOT
            // ./ROOT/dir1
            // ./ROOT/dir1/file.txt
            // ./ROOT/dir1/empty/ ***
        }

19 View Source File : RunnerWebProxyL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void IsNotUseRawHttpClientHandler()
        {
            List<string> sourceFiles = Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Common"),
                    "*.cs",
                    SearchOption.AllDirectories).ToList();
            sourceFiles.AddRange(Directory.GetFiles(
                     TestUtil.GetProjectPath("Runner.Listener"),
                     "*.cs",
                     SearchOption.AllDirectories));
            sourceFiles.AddRange(Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Worker"),
                    "*.cs",
                    SearchOption.AllDirectories));

            List<string> badCode = new List<string>();
            foreach (string sourceFile in sourceFiles)
            {
                // Skip skipped files.
                if (SkippedFiles.Any(s => sourceFile.Contains(s)))
                {
                    continue;
                }

                // Skip files in the obj directory.
                if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
                {
                    continue;
                }

                int lineCount = 0;
                foreach (string line in File.ReadAllLines(sourceFile))
                {
                    lineCount++;
                    if (NewHttpClientHandlerRegex.IsMatch(line))
                    {
                        badCode.Add($"{sourceFile} (line {lineCount})");
                    }
                }
            }

            replacedert.True(badCode.Count == 0, $"The following code is using Raw HttpClientHandler() which will not follow the proxy setting agent have. Please use HostContext.CreateHttpClientHandler() instead.\n {string.Join("\n", badCode)}");
        }

19 View Source File : RunnerWebProxyL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void IsNotUseRawHttpClient()
        {
            List<string> sourceFiles = Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Common"),
                    "*.cs",
                    SearchOption.AllDirectories).ToList();
            sourceFiles.AddRange(Directory.GetFiles(
                     TestUtil.GetProjectPath("Runner.Listener"),
                     "*.cs",
                     SearchOption.AllDirectories));
            sourceFiles.AddRange(Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Worker"),
                    "*.cs",
                    SearchOption.AllDirectories));

            List<string> badCode = new List<string>();
            foreach (string sourceFile in sourceFiles)
            {
                // Skip skipped files.
                if (SkippedFiles.Any(s => sourceFile.Contains(s)))
                {
                    continue;
                }

                // Skip files in the obj directory.
                if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
                {
                    continue;
                }

                int lineCount = 0;
                foreach (string line in File.ReadAllLines(sourceFile))
                {
                    lineCount++;
                    if (NewHttpClientRegex.IsMatch(line))
                    {
                        badCode.Add($"{sourceFile} (line {lineCount})");
                    }
                }
            }

            replacedert.True(badCode.Count == 0, $"The following code is using Raw HttpClient() which will not follow the proxy setting agent have. Please use New HttpClient(HostContext.CreateHttpClientHandler()) instead.\n {string.Join("\n", badCode)}");
        }

19 View Source File : SolutionDirectory.cs
License : MIT License
Project Creator : adamant

public static string Get()
        {
            var directory = Directory.GetCurrentDirectory() ?? throw new InvalidOperationException("Could not get current directory");
            while (directory != null && !Directory.GetFiles(directory, "*.sln", SearchOption.TopDirectoryOnly).Any())
            {
                directory = Path.GetDirectoryName(directory) ?? throw new InvalidOperationException("Null directory name");
            }
            return directory ?? throw new InvalidOperationException("Compiler is confused, this can't be null");
        }

19 View Source File : DefaultTranslationsProvider.cs
License : MIT License
Project Creator : adams85

private Dictionary<(string Location, string Culture), POCatalog> LoadFiles()
        {
            return Directory.GetFiles(_translationsBasePath, FileNamePattern, SearchOption.AllDirectories)
                .Select(LoadFile)
                .Where(item => item != null)
                .ToDictionary(item => (item!.Value.Location, item.Value.Culture), item => item!.Value.Catalog);
        }

19 View Source File : ValidateCopiedFoldersIntegrity.cs
License : MIT License
Project Creator : adrenak

static string CreateMd5ForFolder(string path)
        {
            // replaceduming you want to include nested folders
            var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
                                 .OrderBy(p => p).ToList();

            MD5 md5 = MD5.Create();

            for (int i = 0; i < files.Count; i++)
            {
                string file = files[i];

                // hash path
                string relativePath = file.Substring(path.Length + 1);
                byte[] pathBytes = Encoding.UTF8.GetBytes(relativePath.ToLower());
                md5.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);

                // hash contents
                byte[] contentBytes = File.ReadAllBytes(file);
                if (i == files.Count - 1)
                    md5.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
                else
                    md5.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
            }

            return BitConverter.ToString(md5.Hash).Replace("-", "").ToLower();
        }

19 View Source File : FileSystem.cs
License : MIT License
Project Creator : AdrianWilczynski

public static IEnumerable<string> GetFilesWithExtension(string directoryPath, string extension)
           => Directory.GetFiles(directoryPath, $"*.{extension}", SearchOption.AllDirectories);

19 View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

[Fact]
        public void ConvertDirectoryIntoProvidedOutputDirectory()
        {
            Prepare(nameof(ConvertDirectoryIntoProvidedOutputDirectory));

            var inputDirectoryPath = Path.Join(nameof(ConvertDirectoryIntoProvidedOutputDirectory), "Input");
            Directory.CreateDirectory(inputDirectoryPath);

            Directory.SetCurrentDirectory(inputDirectoryPath);

            try
            {
                File.WriteAllText("File1.cs", "clreplaced Item8 { }");
                File.WriteAllText("File2.cs", "clreplaced Item9 { }");
                File.WriteAllText("File3.cs", "clreplaced Item10 { }");

                var outputDirectoryPath = Path.Join("..", "Output");

                _convertCommand.Input = ".";
                _convertCommand.Output = outputDirectoryPath;

                _convertCommand.OnExecute();

                var convertedFiles = Directory.GetFiles(outputDirectoryPath)
                    .Where(f => f.EndsWith(".ts"))
                    .Select(Path.GetFileName);

                replacedert.Equal(new[] { "file1.ts", "file2.ts", "file3.ts" }, convertedFiles);
            }
            finally
            {
                Directory.SetCurrentDirectory(Path.Join("..", ".."));
            }
        }

19 View Source File : Background.cs
License : GNU General Public License v3.0
Project Creator : aelariane

protected override void OnEnable()
        {
            string[] allImages = System.IO.Directory.GetFiles(Directory);
            if (allImages.Length == 0)
            {
                texture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
                texture.SetPixel(0, 0, new Color(0f, 36f / 255f, 36f / 255f, 1f));
                texture.Apply();
                return;
            }
            var random = allImages[UnityEngine.Random.Range(0, allImages.Length)].Substring(Directory.Length);
            if (random.EndsWith(".ogv"))
            {
                movie = LoadVideo(random);
                if (movie != null)
                {
                    movie.loop = true;
                    movie.Play();
                }
            }
            else
            {
                texture = LoadTexture(random, "");
            }
            screenRect = new Rect(0f, 0f, Style.ScreenWidth, Style.ScreenHeight);
            style = Helper.CreateStyle(TextAnchor.LowerCenter, FontStyle.Bold, 25, false, new Color(0.95f, 0.95f, 0.95f));
            style.richText = true;
            style.font = Anarchyreplacedets.Load<Font>(Style.FontName);
            AnarchyManager.MainMenu.Enable();
        }

19 View Source File : Background.cs
License : GNU General Public License v3.0
Project Creator : aelariane

protected override void OnEnable()
        {
            string[] allImages = System.IO.Directory.GetFiles(Directory);
            if (allImages.Length == 0)
            {
                texture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
                texture.SetPixel(0, 0, new Color(0f, 36f / 255f, 36f / 255f, 1f));
                texture.Apply();
                return;
            }
            var random = allImages[UnityEngine.Random.Range(0, allImages.Length)].Substring(Directory.Length);
            if (random.EndsWith(".ogv"))
            {
                movie = LoadVideo(random, "");
                if (movie != null)
                {
                    movie.loop = true;
                    movie.Play();
                }
            }
            else
            {
                texture = LoadTexture(random, "");
            }
            screenRect = new Rect(0f, 0f, Style.ScreenWidth, Style.ScreenHeight);
            style = Helper.CreateStyle(TextAnchor.LowerCenter, FontStyle.Bold, 25, false, new Color(0.95f, 0.95f, 0.95f));
            style.richText = true;
            style.font = Anarchyreplacedets.Load<Font>(Style.FontName);
            AnarchyManager.MainMenu.Enable();

        }

19 View Source File : RacingLogic.cs
License : GNU General Public License v3.0
Project Creator : aelariane

protected override void OnRestart()
        {
            needShowFinishers = false;
            RaceStart = false;
            FinishersCount = 0;
            if (FengGameManagerMKII.Level.Name.Contains("Custom"))
            {
                needDestroyDoors = true;
            }
            nonStopDictionary.Clear();
            doorsDestroyed = false;
            if (PhotonNetwork.IsMasterClient && GameModes.RacingStartTime.Enabled)
            {
                OnRequireStatus();
            }

            if (PhotonNetwork.IsMasterClient)
            {
                if (nextRacingScript.Length > 0)
                {
                    CustomLevel.currentScript = nextRacingScript;
                    nextRacingScript = string.Empty;
                }

                if (GameModes.AutoPickNextMap.Enabled)
                {
                    if (CurrentRound % GameModes.AutoPickNextMap.GetInt(0) == 0)
                    {
                        string[] fileNames = System.IO.Directory.GetFiles(Anarchy.UI.CustomPanel.MapsPath)
                            .Select(x => x)
                            .Where(x => GameModes.AutoPickNextMapFilter.Value.Trim().Length == 0 || x.ToLower().Contains(GameModes.AutoPickNextMapFilter.Value.Trim().ToLower()))
                            .ToArray();

                        if (fileNames.Length > 0)
                        {
                            var file = new System.IO.FileInfo(fileNames[Random.Range(0, fileNames.Length)]);
                            nextRacingScript = System.IO.File.ReadAllText(file.FullName);
                            if (GameModes.AnnounceMapSwitch)
                            {
                                FengGameManagerMKII.FGM.BasePV.RPC("Chat", PhotonTargets.All, new object[] { $"<color=#{User.MainColor}>[Map-Switch] Next map is set: <i><color=#{User.SubColor}>{file.Name.Replace(file.Extension, "")}</color></i></color>", "" });
                            }
                        }
                    }
                }
            }
        }

19 View Source File : Helpers.cs
License : GNU General Public License v3.0
Project Creator : Aetsu

public static void CalculateMD5Files(string folder)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("     Calculating md5...");
            Console.ResetColor();
            string[] fileList = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories);
            List<string> md5List = new List<string>();
            foreach (string filename in fileList)
            {
                using (var md5 = MD5.Create())
                {
                    using (var stream = File.OpenRead(filename))
                    {
                        var hash = md5.ComputeHash(stream);
                        md5List.Add(filename + " - " + BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant());
                    }
                }
            }
            File.WriteAllLines(Path.Combine(new string[] { folder, "md5.txt" }), md5List);
        }

19 View Source File : MetadataProvider.cs
License : MIT License
Project Creator : afaniuolo

private string[] GetMetadataFileList()
		{
			var metadataDirPath = _appSettings.metadataFolderRelativePath;
			return Directory.GetFiles(metadataDirPath, "*.json", SearchOption.AllDirectories);
		}

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void GetAllFiles(List<string> fields, string path, string ext)
        {
            if (!Directory.Exists(path))
            {
                return;
            }
            fields.AddRange(Directory.GetFiles(path, ext, SearchOption.TopDirectoryOnly));
            foreach (var ch in Directory.GetDirectories(path))
            {
                GetAllFiles(fields, ch, ext);
            }
        }

19 View Source File : StickerEditor.cs
License : MIT License
Project Creator : agens-no

public static void AddStickerSequence(SerializedProperty sequence, SerializedProperty name, SerializedProperty fps, SerializedProperty frames)
        {
            var path = EditorUtility.OpenFilePanelWithFilters("Select Sticker Sequence", string.Empty, new string[] { "Image", "png,gif,jpg,jpeg" });
            var folder = Path.GetDirectoryName(path);
            //var folder = EditorUtility.OpenFolderPanel("Select Sticker Sequence", string.Empty, string.Empty);
            Debug.Log("path: " + path + " folder: " + folder);
            var files = Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(StickerEditorUtility.HasValidFileExtension).ToList();
            files.Sort();

            sequence.boolValue = true;
            var dir = new DirectoryInfo(folder);
            name.stringValue = dir.Name;
            fps.intValue = 15;

            frames.arraySize = files.Count;
            for (int index = 0; index < files.Count; index++)
            {
                var file = files[index];
                var projectPath = Application.dataPath;
                var filePath = file.Replace(projectPath, "replacedets");
                Debug.Log("loaded texture at " + filePath);
                var replacedet = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(filePath);
                var prop = frames.GetArrayElementAtIndex(index);
                prop.objectReferenceValue = replacedet;
            }
        }

19 View Source File : StickerPackEditor.cs
License : MIT License
Project Creator : agens-no

private void ImportFromFolder()
        {
            var folder = EditorUtility.OpenFolderPanel("Import Stickers", EditorPrefs.GetString("Stickers.ImportFolder"), string.Empty);
            if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
            {
                EditorPrefs.SetString("Stickers.ImportFolder", folder);

                var files = Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(StickerEditorUtility.HasValidFileExtension).ToArray();
                foreach (var file in files)
                {
                    var sticker = OnAddCallback(false);
                    var texture = LoadreplacedetFromPath<Texture2D>(file);
                    if (texture != null)
                    {
                        sticker.Frames[0] = texture;
                        sticker.name = texture.name;
                        sticker.Name = texture.name;
                    }
                }

                var directories = Directory.GetDirectories(folder);
                foreach (var directory in directories)
                {
                    if (string.IsNullOrEmpty(directory))
                    {
                        continue;
                    }

                    var sticker = OnAddCallback(true);
                    sticker.Frames = new List<Texture2D>(1);

                    var dirInfo = new DirectoryInfo(directory);

                    sticker.name = dirInfo.Name;
                    sticker.Name = dirInfo.Name;

                    files = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(StickerEditorUtility.HasValidFileExtension).ToArray();
                    for (var index = 0; index < files.Length; index++)
                    {
                        var file = files[index];
                        var texture = LoadreplacedetFromPath<Texture2D>(file);
                        if (texture != null)
                        {
                            sticker.Frames.Add(texture);
                        }
                    }
                }
            }
        }

19 View Source File : StickerPackEditor.cs
License : MIT License
Project Creator : agens-no

private void ImportFromFolder()
        {
            var folder = EditorUtility.OpenFolderPanel("Import Stickers", EditorPrefs.GetString("Stickers.ImportFolder"), string.Empty);
            if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
            {
                EditorPrefs.SetString("Stickers.ImportFolder", folder);

                var files = Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(StickerEditorUtility.HasValidFileExtension).ToArray();
                foreach (var file in files)
                {
                    var sticker = OnAddCallback(false);
                    var texture = LoadreplacedetFromPath<Texture2D>(file);
                    if (texture != null)
                    {
                        sticker.Frames[0] = texture;
                        sticker.name = texture.name;
                        sticker.Name = texture.name;
                    }
                }

                var directories = Directory.GetDirectories(folder);
                foreach (var directory in directories)
                {
                    if (string.IsNullOrEmpty(directory))
                    {
                        continue;
                    }

                    var sticker = OnAddCallback(true);
                    sticker.Frames = new List<Texture2D>(1);

                    var dirInfo = new DirectoryInfo(directory);

                    sticker.name = dirInfo.Name;
                    sticker.Name = dirInfo.Name;

                    files = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(StickerEditorUtility.HasValidFileExtension).ToArray();
                    for (var index = 0; index < files.Length; index++)
                    {
                        var file = files[index];
                        var texture = LoadreplacedetFromPath<Texture2D>(file);
                        if (texture != null)
                        {
                            sticker.Frames.Add(texture);
                        }
                    }
                }
            }
        }

19 View Source File : StickerPackEditor.cs
License : MIT License
Project Creator : agens-no

private void LoadIconsFromFolder()
        {
            var folder = EditorUtility.OpenFolderPanel("Select Sticker Icon Folder", string.Empty, string.Empty);
            var files = Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                .Where(StickerEditorUtility.HasValidFileExtension).ToList();
            files.Sort();

            overrideIcon.boolValue = true;

            var texturesFound = new List<Texture2D>();

            foreach (var file in files)
            {
                texturesFound.Add(LoadreplacedetFromPath<Texture2D>(file));
            }

            for (var i = 0; i < iconProperties.Length; i++)
            {
                iconProperties[i].objectReferenceValue = texturesFound.Find(t => t.width == (int)iconTextureSizes[i].x && t.height == (int)iconTextureSizes[i].y);
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

private void OnDragDrop(object sender, DragEventArgs e)
        {
            if (!e.Effects.HasFlag(DragDropEffects.Copy))
                return;
            if (MessageBox.Show("You are about to import the files." + Environment.NewLine
                    + "This will import all files to the smallest bundle of all loaded bundles (doesn't contain which were filtered)." + Environment.NewLine
                    + "The dropped paths must contain Bundles2." + Environment.NewLine
                    + "All files to be imported must be defined by the _.index.bin." + Environment.NewLine
                    + "Are you sure you want to do this?",
                    "Import Confirm",
                    MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                var droppedFileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
                var checkedPaths = new Dictionary<string, string>();

                int l = loadedBundles[0].UncompressedSize;
                BundleRecord bundleToSave = loadedBundles[0];
                RunBackground(() =>
                {
                    Dispatcher.Invoke(() => { CurrentBackground.Message.Text = "Checking files . . ."; });
                    foreach (var f in droppedFileNames)
                    {
                        if (Directory.Exists(f))
                            foreach (var p in Directory.GetFiles(f, "*", SearchOption.AllDirectories))
                            {
                                var i = p.IndexOf("Bundles2");
                                if (i >= 0 && i + 9 < p.Length)
                                {
                                    var path = p.Substring(i + 9).Replace("\\", "/");
                                    if (!ic.Paths.Contains(path))
                                    {
                                        MessageBox.Show("The index didn't define the file:" + Environment.NewLine + path, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                        return;
                                    }
                                    checkedPaths.Add(p, path);
                                }
                            }
                        else
                        {
                            var i = f.IndexOf("Bundles2");
                            if (i >= 0 && i + 9 < f.Length)
                            {
                                var path = f.Substring(i + 9).Replace("\\", "/");
                                if (!ic.Paths.Contains(path))
                                {
                                    MessageBox.Show("The index didn't define the file:" + Environment.NewLine + path, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                    return;
                                }
                                checkedPaths.Add(f, path);
                            }
                        }
                    }

                    foreach (var b in loadedBundles)
                    {
                        if (b.UncompressedSize < l)
                        {
                            l = b.UncompressedSize;
                            bundleToSave = b;
                        }
                    }
                    string str = "Imported {0}/" + checkedPaths.Count.ToString() + " Files";
                    int count = 0;
                    foreach (var f in checkedPaths)
                    {
                        var fr = ic.FindFiles[IndexContainer.FNV1a64Hash(f.Value)];
                        fr.Write(File.ReadAllBytes(f.Key));
                        fr.Move(bundleToSave);
                        ++count;
                        Dispatcher.Invoke(() => { CurrentBackground.Message.Text = string.Format(str, count); });
                    }
                    if(count > 0)
                        changed.Add(bundleToSave);
                });
                ButtonSave.IsEnabled = true;
                MessageBox.Show("Imported " + checkedPaths.Count.ToString() + " files into " + bundleToSave.Name, "Done");
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

private void OnButtonAddClick(object sender, RoutedEventArgs e)
        {
            BundleRecord bundleToSave = (BundleRecord)(((ItemModel)View1.SelectedItem)?.Record);
            if (MessageBox.Show(
                    (bundleToSave == null ? "This will import all files to the smallest of all loaded bundles (doesn't contain which were filtered)." : "This will import all files to \"" + bundleToSave.Name + "\"") + Environment.NewLine
                    + "All files to be imported must be defined by the _.index.bin." + Environment.NewLine
                    + "Are you sure you want to do this?",
                    "Import Confirm",
                    MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                var fbd = new OpenFolderDialog();
                if (fbd.ShowDialog() == true)
                {
                    var fileNames = Directory.GetFiles(fbd.DirectoryPath, "*", SearchOption.AllDirectories);
                    RunBackground(() =>
                    {
                        Dispatcher.Invoke(() => { CurrentBackground.Message.Text = "Checking files . . ."; });
                        foreach (var f in fileNames)
                        {
                            var path = f.Remove(0, fbd.DirectoryPath.Length + 1).Replace("\\", "/");
                            if (!ic.Paths.Contains(path))
                            {
                                MessageBox.Show("The index didn't define the file:" + Environment.NewLine + path, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                        }

                        if (bundleToSave == null)
                            bundleToSave = ic.GetSmallestBundle(loadedBundles);

                        string str = "Imported {0}/" + fileNames.Length.ToString() + " Files";
                        int count = 0;
                        foreach (var f in fileNames)
                        {
                            var path = f.Remove(0, fbd.DirectoryPath.Length + 1).Replace("\\", "/");
                            var fr = ic.FindFiles[IndexContainer.FNV1a64Hash(path)];
                            fr.Write(File.ReadAllBytes(f));
                            fr.Move(bundleToSave);
                            ++count;
                            Dispatcher.Invoke(() => { CurrentBackground.Message.Text = string.Format(str, count); });
                        }
                        if (count > 0)
                            changed.Add(bundleToSave);
                    });
                    ButtonSave.IsEnabled = true;
                    MessageBox.Show("Imported " + fileNames.Length.ToString() + " files into " + bundleToSave.Name, "Done");
                }
            }
        }

19 View Source File : GGPKContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public virtual void GetFileList(string ROOTPath, ICollection<KeyValuePair<IFileRecord, string>> list, string searchPattern = "*", string regex = null) {
            var files = Directory.GetFiles(ROOTPath, searchPattern, SearchOption.AllDirectories);
            foreach (var f in files) {
                var path = f[(ROOTPath.Length + 1)..];
                if ((regex == null || Regex.IsMatch(path, regex)) && FindRecord(path) is IFileRecord ifr)
                    list.Add(new(ifr, f));
			}
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : airbus-cert

static void Main(string[] args)
        {
            // Get list of yara rules
            string[] ruleFiles = Directory.GetFiles(@"e:\yara-db\rules\", "*.yara", SearchOption.AllDirectories)
                .ToArray();

            // Get list of samples to check
            string[] samples = new[]
            {
                @"e:\malware-samples\", // directory
                @"e:\speficic-samples\sample1.exe" // file
            };

            // Initialize yara context
            using (YaraContext ctx = new YaraContext())
            {
                // Compile list of yara rules
                CompiledRules rules = null;
                using (var compiler = new Compiler())
                {
                    foreach (var yara in ruleFiles)
                    {
                        compiler.AddRuleFile(yara);
                    }

                    rules = compiler.Compile();

                    Console.WriteLine($"* Compiled");
                }

                if (rules != null)
                {
                    // Initialize the scanner
                    var scanner = new Scanner();

                    // Go through all samples
                    foreach (var sample in samples)
                    {
                        // If item is file, scan the file
                        if (File.Exists(sample))
                        {
                            ScanFile(scanner, sample, rules);
                        }
                        // If item is directory, scan the directory
                        else
                        {
                            if (Directory.Exists(sample))
                            {
                                DirectoryInfo dirInfo = new DirectoryInfo(sample);

                                foreach (FileInfo fi in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories))
                                    ScanFile(scanner, fi.FullName, rules);
                            }
                        }
                    }

                }

            }
        }

19 View Source File : FileSystemStore.cs
License : MIT License
Project Creator : aishang2015

public Task<IEnumerable<IFileStoreEntry>> GetDirectoryContentAsync(string path = null, bool includeSubDirectories = false)
        {
            var physicalPath = GetPhysicalPath(path);
            var results = new List<IFileStoreEntry>();

            if (!Directory.Exists(physicalPath))
            {
                return Task.FromResult((IEnumerable<IFileStoreEntry>)results);
            }

            // Add directories.
            results.AddRange(
                Directory
                    .GetDirectories(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Select(f =>
                    {
                        var fileSystemInfo = new PhysicalDirectoryInfo(new DirectoryInfo(f));
                        var fileRelativePath = f.Substring(_fileSystemRootPath.Length);
                        var filePath = this.NormalizePath(fileRelativePath);
                        return new FileSystemStoreEntry(filePath, fileSystemInfo);
                    }));

            // Add files.
            results.AddRange(
                Directory
                    .GetFiles(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Select(f =>
                    {
                        var fileSystemInfo = new PhysicalFileInfo(new FileInfo(f));
                        var fileRelativePath = f.Substring(_fileSystemRootPath.Length);
                        var filePath = this.NormalizePath(fileRelativePath);
                        return new FileSystemStoreEntry(filePath, fileSystemInfo);
                    }));

            return Task.FromResult((IEnumerable<IFileStoreEntry>)results);
        }

19 View Source File : PluginManager.cs
License : MIT License
Project Creator : AkiniKites

public IEnumerable<T> LoadAll<T>()
        {
            Paths.CheckDirectory(PluginDir);
            var dlls = Directory.GetFiles(PluginDir, PluginPattern, SearchOption.TopDirectoryOnly);

            foreach (string dll in dlls)
            {
                foreach (var loadedType in replacedemblyLoader.LoadTypes<T>(dll))
                {
                    yield return loadedType;
                }
            }
        }

19 View Source File : Archiver.cs
License : MIT License
Project Creator : AkiniKites

private PackList GetPackFiles(string dir, HashSet<string> fileFilter, string ext)
        {
            var files = Directory.GetFiles(dir, $"*{ext}", SearchOption.AllDirectories)
                .Where(x=> fileFilter == null || fileFilter.Contains(Path.GetFileName(x)))
                .OrderBy(x => x).ToList();

            //move patch files to end, same as game load order
            int moved = 0;
            for (int i = 0; i < files.Count - moved; i++)
            {
                if (Path.GetFileName(files[i]).StartsWith(PatchPrefix))
                {
                    var file = files[i];
                    files.RemoveAt(i);
                    files.Add(file);

                    i--;
                    moved++;
                }
            }

            return new PackList(files);
        }

19 View Source File : AssetBundleFilesAnalyze.cs
License : MIT License
Project Creator : akof1314

private static List<replacedetBundleFileInfo> replacedyzAllFiles(string directoryPath)
        {
            List<replacedetBundleFileInfo> infos = new List<replacedetBundleFileInfo>();
            string bom = "Unity";
            char[] flag = new char[5];
            string[] files = Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                using (StreamReader streamReader = new StreamReader(file))
                {
                    if (streamReader.Read(flag, 0, flag.Length) == flag.Length && new string(flag) == bom)
                    {
                        replacedetBundleFileInfo info = new replacedetBundleFileInfo
                        {
                            name = file.Substring(directoryPath.Length + 1),
                            path = file,
                            rootPath = directoryPath,
                            size = streamReader.BaseStream.Length,
                            directDepends = new string[] { },
                            allDepends = new string[] { }
                        };
                        infos.Add(info);
                    }
                }
            }

            return infos;
        }

19 View Source File : TechLogExporter.cs
License : MIT License
Project Creator : akpaevj

public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            _logger?.LogInformation("Exporter is started");

            _cancellationToken = cancellationToken;
            _cancellationToken.Register(() => _readBlock.Complete());

            var logFiles = Directory.GetFiles(_settings.LogFolder, "*.log", SearchOption.AllDirectories);

            foreach (var logFile in logFiles)
                StartFileReading(logFile);

            if (_settings.LiveMode)
                InitializeWatcher();
            else
                _readBlock.Complete();

            await _writeBlock.Completion;

            _logger?.LogInformation("Exporter is stopped");
        }

19 View Source File : ScriptAssetOpener.cs
License : MIT License
Project Creator : akof1314

private static bool TryOpenVisualStudioFile(string file, int line)
        {
            string dirPath = file;

            do
            {
                dirPath = Path.GetDirectoryName(dirPath);
                if (!string.IsNullOrEmpty(dirPath) && Directory.Exists(dirPath))
                {
                    var files = Directory.GetFiles(dirPath, "*.sln", SearchOption.TopDirectoryOnly);
                    if (files.Length > 0)
                    {
                        OpenVisualStudioFile(files[0], file, line);
                        return true;
                    }
                }
                else
                {
                    break;
                }
            } while (true);

            return false;
        }

See More Examples