System.IO.Directory.GetFiles(string)

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

1730 Examples 7

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

private void CheckCleanup(string uid) {
            string dir = GetUserDir(uid);
            if (Directory.GetFiles(dir).Length == 0)
                DeleteRawAll(dir);
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override void CopyTo(UserData other) {
            using UserDataBatchContext batch = other.OpenBatch();
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);

                Dictionary<string, Type?> types = new();
                replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();

                foreach (string uid in GetAll()) {
                    PrivateUserInfo info = Load<PrivateUserInfo>(uid);
                    other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());

                    foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
                        string name = Path.GetFileNameWithoutExtension(path);
                        if (name == typeof(PrivateUserInfo).FullName)
                            continue;

                        if (!types.TryGetValue(name, out Type? type)) {
                            foreach (replacedembly asm in asms)
                                if ((type = asm.GetType(name)) != null)
                                    break;
                            types[name] = type;
                        }

                        using Stream stream = File.OpenRead(path);
                        other.InsertData(uid, name, type, stream);
                    }

                    string dir = Path.Combine(UserRoot, uid, "data");
                    if (Directory.Exists(dir)) {
                        foreach (string path in Directory.GetFiles(dir)) {
                            string name = Path.GetFileName(path);
                            using Stream stream = File.OpenRead(path);
                            other.InsertFile(uid, name, stream);
                        }
                    }
                }
            }
        }

19 Source : Program.cs
with MIT License
from 0x0ade

static void Main(string[] args) {
            string inputDir;
            if (args.Length != 1 || !Directory.Exists(inputDir = args[0])) {
                Console.Error.WriteLine("Usage: inputdir");
                return;
            }

            foreach (string path in Directory.GetFiles(inputDir)) {
                Console.WriteLine($"Stripping: {path}");
                Strip(path);
            }
        }

19 Source : Program.cs
with MIT License
from 0x0ade

static void Main(string[] args) {
            // Required for the relative extra paths to work properly.
            if (!File.Exists("MonoMod.RuntimeDetour.dll"))
                Environment.CurrentDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            string inputDir, outputDir;
            if (args.Length != 2 ||
                !Directory.Exists(inputDir = args[0]) ||
                !Directory.Exists(outputDir = args[1])) {
                Console.Error.WriteLine("Usage: inputdir outputdir");
                return;
            }

            // Check that the files exist.
            if (!VerifyFile(out string inputXNA, inputDir, "Terraria.XNA.exe"))
                return;
            if (!VerifyFile(out string inputFNA, inputDir, "Terraria.FNA.exe"))
                return;

            // Strip or copy.
            foreach (string path in Directory.GetFiles(inputDir)) {
                if (!path.EndsWith(".exe") && !path.EndsWith(".dll")) {
                    Console.WriteLine($"Copying: {path}");
                    File.Copy(path, Path.Combine(outputDir, Path.GetFileName(path)));
                    continue;
                }

                Console.WriteLine($"Stripping: {path}");
                Stripper.Strip(path);
            }

            // Generate hooks.
            string hooksXNA = Path.Combine(outputDir, "Windows.Pre.dll");
            string hooksFNA = Path.Combine(outputDir, "Mono.Pre.dll");
            GenHooks(inputXNA, hooksXNA);
            GenHooks(inputFNA, hooksFNA);

            // Merge generated .dlls and MonoMod into one .dll per environment.
            string[] extrasMod = {
                "TerrariaHooks.dll",
                "MonoMod.exe",
                "MonoMod.RuntimeDetour.dll",
                "MonoMod.Utils.dll"
            };
            Repack(hooksXNA, extrasMod, Path.Combine(outputDir, "Windows.dll"), "TerrariaHooks.dll");
            File.Delete(hooksXNA);
            Repack(hooksFNA, extrasMod, Path.Combine(outputDir, "Mono.dll"), "TerrariaHooks.dll");
            File.Delete(hooksFNA);
        }

19 Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 Source : Utils.cs
with Apache License 2.0
from 214175590

public static void CopyDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;

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

            string[] files = Directory.GetFiles(fromDir);
            foreach (string formFileName in files)
            {
                string fileName = Path.GetFileName(formFileName);
                string toFileName = Path.Combine(toDir, fileName);
                File.Copy(formFileName, toFileName);
            }
            string[] fromDirs = Directory.GetDirectories(fromDir);
            foreach (string fromDirName in fromDirs)
            {
                string dirName = Path.GetFileName(fromDirName);
                string toDirName = Path.Combine(toDir, dirName);
                CopyDir(fromDirName, toDirName);
            }
        }

19 Source : TemplateGenerator.cs
with MIT License
from 2881099

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

19 Source : DynamicProxy.cs
with MIT License
from 2881099

static replacedembly CompileCode(string cscode)
    {

        var files = Directory.GetFiles(Directory.GetParent(Type.GetType("FreeSql.DynamicProxy, FreeSql.DynamicProxy").replacedembly.Location).FullName);
        using (var compiler = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("cs"))
        {
            var objCompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
            objCompilerParameters.Referencedreplacedemblies.Add("System.dll");
            objCompilerParameters.Referencedreplacedemblies.Add("System.Core.dll");
            objCompilerParameters.Referencedreplacedemblies.Add("FreeSql.DynamicProxy.dll");
            foreach (var dll in files)
            {
                if (!dll.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
                    !dll.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) continue;

                Console.WriteLine(dll);
                var dllName = string.Empty;
                var idx = dll.LastIndexOf('/');
                if (idx != -1) dllName = dll.Substring(idx + 1);
                else
                {
                    idx = dll.LastIndexOf('\\');
                    if (idx != -1) dllName = dll.Substring(idx + 1);
                }
                if (string.IsNullOrEmpty(dllName)) continue;
                try
                {
                    var replaced = replacedembly.LoadFile(dll);
                    objCompilerParameters.Referencedreplacedemblies.Add(dllName);
                }
                catch
                {

                }
            }
            objCompilerParameters.GenerateExecutable = false;
            objCompilerParameters.GenerateInMemory = true;

            var cr = compiler.CompilereplacedemblyFromSource(objCompilerParameters, cscode);

            if (cr.Errors.Count > 0)
                throw new DynamicProxyException($"FreeSql.DynamicProxy 失败提示:{cr.Errors[0].ErrorText} {cscode}", null);

            return cr.Compiledreplacedembly;
        }
    }

19 Source : WebContentFolderHelper.cs
with MIT License
from 52ABP

private static bool DirectoryContains(string directory, string fileName)
        {
            return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
        }

19 Source : ExtendableEnums.cs
with MIT License
from 7ark

static KeyValuePair<string, string> FindAllScriptFiles(string startDir, string enumToFind)
    {
        try
        {
            foreach (string file in Directory.GetFiles(startDir))
            {
                if ((file.Contains(".cs") || file.Contains(".js")) && !file.Contains(".meta"))
                {
                    string current = File.ReadAllText(file);
                    string currentTrimmed = current.Replace(" ", "").Replace("\n", "").Replace("\t", "").Replace("\r", "");
                    if (currentTrimmed.Contains(enumToFind.Replace(" ", "") + "{"))
                        return new KeyValuePair<string, string>(current, file);
                }
            }
            foreach (string dir in Directory.GetDirectories(startDir))
            {
                KeyValuePair<string, string> result = FindAllScriptFiles(dir, enumToFind);
                if (result.Key != "NOPE")
                    return result;
            }
        }
        catch (System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
        return new KeyValuePair<string, string>("NOPE", "NOPE");
    }

19 Source : TestAmf0Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadBoolean()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/boolean");

            foreach (var file in files)
            {
                var value = bool.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetBoolean(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : TestAmf3Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadBoolean()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/boolean");

            foreach (var file in files)
            {
                var value = bool.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetBoolean(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : TestAmf0Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadNumber()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/number");

            foreach (var file in files)
            {
                var value = double.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetNumber(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : TestAmf3Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadNumber()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/number");

            foreach (var file in files)
            {
                var value = double.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetDouble(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : TestAmf3Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadInteger()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/intenger");

            foreach (var file in files)
            {
                var value = uint.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetUInt29(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : TestAmf3Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadString()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/string");

            foreach (var file in files)
            {
                var value = Path.GetFileNameWithoutExtension(file);
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetString(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : TestAmf0Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadString()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/string");

            foreach (var file in files)
            {
                var value = Path.GetFileNameWithoutExtension(file);
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetString(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : UMAAssetIndexerEditor.cs
with Apache License 2.0
from A7ocin

private void RecursiveScanFoldersForreplacedets(string path)
		{
			var replacedetFiles = System.IO.Directory.GetFiles(path);

			foreach (var replacedetFile in replacedetFiles)
			{
				string Extension = System.IO.Path.GetExtension(replacedetFile).ToLower();
				if (Extension == ".replacedet" || Extension == ".controller" || Extension == ".txt")
				{
					Object o = replacedetDatabase.LoadMainreplacedetAtPath(replacedetFile);

					if (o)
					{
						AddedDuringGui.Add(o);
					}
				}
			}
			foreach (var subFolder in System.IO.Directory.GetDirectories(path))
			{
				RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'));
			}
		}

19 Source : FileChecker.cs
with Apache License 2.0
from AantCoder

private static void generateHashFiles(List<ModelFileInfo> result, ref string rootFolder, string folder, bool level0 = false)
        {
            if (!level0)
            {
                var dirs = Directory.GetDirectories(folder);
                foreach (var subDir in dirs)
                {
                    generateHashFiles(result, ref rootFolder, subDir);
                }
            }

            var files = Directory.GetFiles(folder);
            int fileNamePos = rootFolder.Length + 1;
            var computeHash = new FastComputeHash();
            foreach (var file in files.Where(x => ApproveExt(x)))
            {
                var mfi = new ModelFileInfo()
                {
                    FileName = file.Substring(fileNamePos)
                };
                GetCheckSum(mfi, file, computeHash);
#if DEBUG
                /*
                if (mfi.FileName.Contains("armony"))
                {
                    Loger.Log($"generateHashFiles Harmony: {FileName} {Hash}");
                }*/
#endif
                result.Add(mfi);
            }
            computeHash.Wait();
        }

19 Source : MixedRealityToolkitFiles.cs
with Apache License 2.0
from abist-co-ltd

public static string[] GetFiles(MixedRealityToolkitModuleType module, string mrtkRelativeFolder)
        {
            if (!AreFoldersAvailable)
            {
                Debug.LogWarning("Failed to locate MixedRealityToolkit folders in the project.");
                return null;
            }

            if (mrtkFolders.TryGetValue(module, out HashSet<string> modFolders))
            {
                return modFolders
                    .Select(t => Path.Combine(t, mrtkRelativeFolder))
                    .Where(Directory.Exists)
                    .SelectMany(t => Directory.GetFiles(t))
                    .Select(GetreplacedetDatabasePath)
                    .ToArray();
            }
            return null;
        }

19 Source : OVRScreenshotWizard.cs
with MIT License
from absurd-joy

void OnWizardCreate()
	{
		if ( !replacedetDatabase.IsValidFolder( cubeMapFolder ) )
		{
			if (!CreatereplacedetPath(cubeMapFolder))
			{
				Debug.LogError( "Created path failed: " + cubeMapFolder );
				return;
			}
		}

		bool existingCamera = true;
		bool existingCameraStateSave = true;
		Camera camera = renderFrom.GetComponent<Camera>();
		if (camera == null)
		{
			camera = renderFrom.AddComponent<Camera>();
			camera.farClipPlane = 10000f;
			existingCamera = false;
		}
		else
		{
			existingCameraStateSave = camera.enabled;
			camera.enabled = true;
		}
		// find the last screenshot saved
		if (cubeMapFolder[cubeMapFolder.Length-1] != '/')
		{
			cubeMapFolder += "/";
		}
		int idx = 0;
		string[] fileNames = Directory.GetFiles(cubeMapFolder);
		foreach(string fileName in fileNames)
		{
			if (!fileName.ToLower().EndsWith(".cubemap"))
			{
				continue;
			}
			string temp = fileName.Replace(cubeMapFolder + "vr_screenshot_", string.Empty);
			temp = temp.Replace(".cubemap", string.Empty);
			int tempIdx = 0;
			if (int.TryParse( temp, out tempIdx ))
			{
				if (tempIdx > idx)
				{
					idx = tempIdx;
				}
			}
		}
		string pathName = string.Format("{0}vr_screenshot_{1}.cubemap", cubeMapFolder, (++idx).ToString("d2"));
		Cubemap cubemap = new Cubemap(size, TextureFormat.RGB24, false);

		// render into cubemap
		if ((camera != null) && (cubemap != null))
		{
			// set up cubemap defaults
			OVRCubemapCapture.RenderIntoCubemap(camera, cubemap);
			if (existingCamera)
			{
				camera.enabled = existingCameraStateSave;
			}
			else
			{
				DestroyImmediate(camera);
			}
			// generate a regular texture as well?
			if ( ( saveMode == SaveMode.SaveCubemapScreenshot ) || ( saveMode == SaveMode.SaveBoth ) )
			{
				GenerateTexture(cubemap, pathName);
			}

			if ( ( saveMode == SaveMode.SaveUnityCubemap ) || ( saveMode == SaveMode.SaveBoth ) )
			{
				Debug.Log( "Saving: " + pathName );
				// by default the unity cubemap isn't saved
				replacedetDatabase.Createreplacedet( cubemap, pathName );
				// reimport as necessary
				replacedetDatabase.Savereplacedets();
				// select it in the project tree so developers can find it
				EditorGUIUtility.PingObject( cubemap );
				Selection.activeObject = cubemap;
			}
			replacedetDatabase.Refresh();
		}
	}

19 Source : FileCache.cs
with Apache License 2.0
from acarteas

public override long GetCount(string regionName = null)
        {
            if (regionName == null)
            {
                regionName = "";
            }
            string path = Path.Combine(CacheDir, _cacheSubFolder, regionName);
            if (Directory.Exists(path))
                return Directory.GetFiles(path).Count();
            else
                return 0;
        }

19 Source : HashedFileCacheManager.cs
with Apache License 2.0
from acarteas

public override IEnumerable<string> GetKeys(string regionName = null)
        {
            string region = "";
            if (string.IsNullOrEmpty(regionName) == false)
            {
                region = regionName;
            }
            string directory = Path.Combine(CacheDir, PolicySubFolder, region);
            List<string> keys = new List<string>();
            if (Directory.Exists(directory))
            {
                foreach (string file in Directory.GetFiles(directory))
                {
                    try
                    {
                        SerializableCacheItemPolicy policy = DeserializePolicyData(file);
                        keys.Add(policy.Key);
                    }
                    catch
                    {

                    }
                }
            }
            return keys.ToArray();
        }

19 Source : FSBuilder.cs
with Apache License 2.0
from acblog

public static void EnsureDirectoryEmpty(string path)
        {
            EnsureDirectoryExists(path);
            foreach (var v in Directory.GetFiles(path))
            {
                File.Delete(v);
            }
            foreach (var v in Directory.GetDirectories(path))
            {
                Directory.Delete(v, true);
            }
        }

19 Source : FSExtensions.cs
with Apache License 2.0
from acblog

public static void CopyDirectory(string sourceDirPath, string saveDirPath)
        {
            if (!Directory.Exists(saveDirPath))
            {
                Directory.CreateDirectory(saveDirPath);
            }
            string[] files = Directory.GetFiles(sourceDirPath);

            foreach (string file in files)
            {
                string pFilePath = Path.Join(saveDirPath, Path.GetFileName(file));
                File.Copy(file, pFilePath, true);
            }

            string[] dirs = Directory.GetDirectories(sourceDirPath);
            foreach (string dir in dirs)
            {
                CopyDirectory(dir, Path.Join(saveDirPath, Path.GetFileName(dir)));
            }
        }

19 Source : AppModuleUpgradeTask.cs
with MIT License
from Accelerider

private static string GetModuleInfoRef(string installPath)
        {
            var dllFilePath = Directory
                .GetFiles(installPath)
                .FirstOrDefault(item => ModuleFileRegex.IsMatch(Path.GetFileName(item)));

            return $"file:///{dllFilePath}";
        }

19 Source : FileManager.cs
with GNU General Public License v3.0
from AdamMYoung

public static IList<FolderIcon> LoadFolders()
        {
            var shortcutAppPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory,
                @"..\..\Images\"));

            return Directory.GetFiles(shortcutAppPath)
                .Select(file => new FolderIcon
                {
                    Image = new BitmapImage(new Uri(file)),
                    ImagePath = file
                }).ToList();
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdisonCavani

List<string> FilesArray(string folderPath)
        {
            return new List<string>(Directory.GetFiles(folderPath).Select(Path.GetFileName));
        }

19 Source : SettingsWindowViewModel.cs
with MIT License
from adlez27

public void GenerateRecListFromFolder()
        {
            recList = new ObservableCollection<RecLisreplacedem>();
            var allFiles = Directory.GetFiles(DestinationFolder);
            foreach(var file in allFiles)
            {
                if (Path.GetExtension(file) == ".wav")
                    recList.Add(new RecLisreplacedem(settings,Path.GetFileNameWithoutExtension(file)));
            }
            newRecList = true;
            recListFromFolder = true;
            RecListFile = "List generated from files in folder.";
        }

19 Source : ConvertCommandShould.cs
with MIT License
from AdrianWilczynski

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

            File.WriteAllText(Path.Join(nameof(ConvertDirectory), "File1.cs"), "clreplaced Item1 { }");
            File.WriteAllText(Path.Join(nameof(ConvertDirectory), "File2.cs"), "clreplaced Item2 { }");
            File.WriteAllText(Path.Join(nameof(ConvertDirectory), "File3.cs"), "clreplaced Item3 { }");

            _convertCommand.Input = nameof(ConvertDirectory);

            _convertCommand.OnExecute();

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

            replacedert.Equal(new[] { "file1.ts", "file2.ts", "file3.ts" }, convertedFiles);
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void repacknsp()
        {
            statuslabel.Content = "Repacking NSP Container...";

            string nspbdir = AppDomain.CurrentDomain.BaseDirectory + "\\nspBuild.pyw";
            string[] tmpfiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp");
            string args = String.Join(" ", tmpfiles);

            Process nsb = new Process();
            nsb.StartInfo.FileName = nspbdir;
            nsb.StartInfo.Arguments = args;
            nsb.StartInfo.CreateNoWindow = true;
            nsb.StartInfo.UseShellExecute = true;
            nsb.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            nsb.EnableRaisingEvents = true;

            nsb.Start();

            await Task.Run(() => nsb.WaitForExit());

            nsb.Close(); 

            stopbar();

            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);          

            System.Windows.MessageBox.Show("Congrats this NSP will now work on " + fwlabel.Content + "!");

            statuslabel.Content = "";
            keylabel.Content = "";
            fwlabel.Content = "";
            tidlabel.Content = "";

            onbtn();
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdriaandeJongh

static void SearchFilesInDirectory(string targetDirectory, List<string> fileList)
        {
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
                fileList.Add(fileName);
            
            string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
            foreach (string subdirectory in subdirectoryEntries)
                SearchFilesInDirectory(subdirectory, fileList);
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public override void Entry(IModHelper helper)
        {
            context = this;
            Config = Helper.ReadConfig<ModConfig>();
            if (!Config.EnableMod)
                return;

            try
            {
                if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "audio")))
                    audio = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "audio"));
                else
                {
                    Directory.CreateDirectory(Path.Combine(Helper.DirectoryPath, "audio"));
                    Monitor.Log($"No audio files found. Please put audio files in {Path.Combine(Helper.DirectoryPath, "audio")}.", LogLevel.Warn);
                    return;
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Error loading audio files:\r\n{ex}", LogLevel.Error);
                return;
            }

            Player = new WindowsMediaPlayer();
            Player.PlayStateChange += new _WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
            Player.MediaError += new _WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
            Player.settings.volume = Config.VolumeLevel;

            Helper.Events.GameLoop.GameLaunched += GameLoop_GameLaunched;
            Helper.Events.Input.ButtonPressed += Input_ButtonPressed;
            Helper.Events.Input.ButtonReleased += Input_ButtonReleased;
        }

19 Source : SavePhase.cs
with GNU General Public License v3.0
from Aekras1a

protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            var vr = context.Annotations.Get<Virtualizer>(context, Fish.VirtualizerKey);
            var merge = context.Annotations.Get<ModuleDef>(context, Fish.MergeKey);

            if(merge != null)
                return;

            var tmpDir = Path.GetTempPath();
            var outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
            Directory.CreateDirectory(outDir);

            var rtPath = vr.SaveRuntime(outDir);
            if(context.Packer != null)
            {
#if DEBUG
                var protRtPath = rtPath;
#else
				var protRtPath = ProtectRT(context, rtPath);
#endif
                context.ExternalModules.Add(File.ReadAllBytes(protRtPath));
                foreach(var rule in context.Project.Rules)
                    rule.RemoveWhere(item => item.Id == Parent.Id);
            }
            else
            {
                outDir = Path.GetDirectoryName(rtPath);
                foreach(var file in Directory.GetFiles(outDir))
                {
                    var path = Path.Combine(context.OutputDirectory, Path.GetFileName(file));
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    File.Copy(file, path, true);
                }
            }
        }

19 Source : CustomPanel.cs
with GNU General Public License v3.0
from aelariane

private string Load(int id, string path)
        {
            string[] files = System.IO.Directory.GetFiles(path);
            if (id == -1)
            {
                id = Random.Range(0, files.Length);
            }
            return System.IO.File.ReadAllText(files[id]);
        }

19 Source : CustomPanel.cs
with GNU General Public License v3.0
from aelariane

private string[] LoadFiles(string path)
        {
            string[] files = System.IO.Directory.GetFiles(path);
            if (files.Length == 0)
            {
                return new string[0];
            }
            for (int i = 0; i < files.Length; i++)
            {
                var file = new System.IO.FileInfo(files[i]);
                string name = file.Name;
                if (file.Extension.Length > 0)
                {
                    name = name.Replace(file.Extension, "");
                }
                files[i] = name;
            }
            return files;
        }

19 Source : User.cs
with GNU General Public License v3.0
from aelariane

private static void RefreshProfilesList()
        {
            var temp = System.IO.Directory.GetFiles(directory);
            var tmp =
                (from t in temp
                 where !t.Contains(Example)
                 select t.Remove(0, directory.Length)
                     .Replace(Extension, string.Empty))
                .ToList();
            AllProfiles = tmp.ToArray();
        }

19 Source : Util.cs
with MIT License
from Aeroblast

public static void DeleteEmptyDir(string path)
    {
        if (!Directory.Exists(path)) return;
        foreach (string p in Directory.GetDirectories(path)) DeleteEmptyDir(p);
        if (Directory.GetDirectories(path).Length == 0 && Directory.GetFiles(path).Length == 0)
            Directory.Delete(path);
    }

19 Source : Program.cs
with GNU General Public License v3.0
from Aeroblast

static void ProcPath(string[] args)
        {
            string azw3_path = null;
            string azw6_path = null;
            string dir;
            string p = args[0];
            if (Directory.Exists(p))
            {
                string[] files = Directory.GetFiles(p);
                if (dedrm)
                {
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n).ToLower() == ".azw")
                        {
                            DeDRM(n);
                        }
                    }
                    files = Directory.GetFiles(p);
                }

                foreach (string n in files)
                {
                    if (Path.GetExtension(n).ToLower() == ".azw3")
                    {
                        azw3_path = n;
                    }
                    if (Path.GetExtension(n) == ".res")
                    {
                        azw6_path = n;
                    }
                }
            }
            else
            {
                if (dedrm && Path.GetExtension(p).ToLower() == ".azw")
                {
                    DeDRM(p);
                    dir = Path.GetDirectoryName(p);
                    string[] files = Directory.GetFiles(dir);
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n) == ".res")
                        {
                            azw6_path = n;
                        }
                        if (Path.GetExtension(n).ToLower() == ".azw3")
                        {
                            azw3_path = n;
                        }
                    }
                }
                else
                if (Path.GetExtension(p).ToLower() == ".azw3")
                {
                    azw3_path = p;
                    dir = Path.GetDirectoryName(p);
                    string[] files = Directory.GetFiles(dir);
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n) == ".res")
                        {
                            azw6_path = n;
                            break;
                        }
                    }
                }
                else if (Path.GetExtension(p).ToLower() == ".res")
                {
                    azw6_path = p;
                    dir = Path.GetDirectoryName(p);
                    string[] files = Directory.GetFiles(dir);
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n).ToLower() == ".azw3")
                        {
                            azw3_path = n;
                            break;
                        }
                    }
                }
            }


            Azw3File azw3 = null;
            Azw6File azw6 = null;
            if (azw3_path != null)
            {
                Log.log("==============START===============");
                azw3 = new Azw3File(azw3_path);
            }
            if (azw6_path != null)
                azw6 = new Azw6File(azw6_path);
            if (azw3 != null)
            {
                string auther = "";
                if (azw3.mobi_header.extMeta.id_string.ContainsKey(100))
                {
                    auther = "[" + azw3.mobi_header.extMeta.id_string[100].Split('&')[0] + "] ";
                }
                string outname = auther + azw3.replacedle + ".epub";
                outname = Util.FilenameCheck(outname);
                Epub epub = new Epub(azw3, azw6, rename_xhtml_with_id);
                Log.log(azw3);
                string output_path;
                if (args.Length >= 2 && Directory.Exists(args[1]))
                {
                    output_path = Path.Combine(args[1], outname);
                }
                else
                {
                    string outdir = Path.GetDirectoryName(args[0]);
                    output_path = Path.Combine(outdir, outname);
                }
                if (File.Exists(output_path))
                {
                    Log.log("[Warn]Output already exist.");
                    if (rename_when_exist)
                    {
                        string r_dir = Path.GetDirectoryName(output_path);
                        string r_name = Path.GetFileNameWithoutExtension(output_path);
                        string r_path = Path.Combine(r_dir, r_name);
                        output_path = "";
                        for (int i = 2; i < 50; i++)
                        {
                            string r_test = r_path + "(" + i + ").epub";
                            if (!File.Exists(r_test))
                            {
                                output_path = r_test;
                                break;
                            }
                        }
                        Log.log("[Warn]Save as...");
                    }
                    else if (!overwrite)
                    {
                        Console.WriteLine("Output file already exist. N(Abort,Defualt)/y(Overwrite)/r(Rename)?");
                        Console.WriteLine("Output path:" + output_path);
                        string input = Console.ReadLine().ToLower();
                        if (input == "y")
                        {
                            Log.log("[Warn]Old file will be replaced.");
                        }
                        else if (input == "r")
                        {
                            string r_dir = Path.GetDirectoryName(output_path);
                            string r_name = Path.GetFileNameWithoutExtension(output_path);
                            string r_path = Path.Combine(r_dir, r_name);
                            output_path = "";
                            for (int i = 2; i < 50; i++)
                            {
                                string r_test = r_path + "(" + i + ").epub";
                                if (!File.Exists(r_test))
                                {
                                    output_path = r_test;
                                    break;
                                }
                            }
                            Log.log("[Warn]Save as...");
                        }
                        else
                        {
                            Log.log("[Error]Operation aborted. You can use --overwrite or --rename-when-exist to avoid pause.");
                            output_path = "";
                        }

                    }
                    else
                    {
                        Log.log("[Warn]Old file will be replaced.");
                    }
                }
                if (output_path != "")
                    epub.Save(output_path);
                Log.log("azw3 source:" + azw3_path);
                if (azw6_path != null)
                    Log.log("azw6 source:" + azw6_path);
            }
            else
            {
                Console.WriteLine("Cannot find .azw3 file in " + p);
            }
        }

19 Source : Util.cs
with MIT License
from Aeroblast

public static void DeleteDir(string path)
    {
        if (!Directory.Exists(path)) return;
        foreach (string p in Directory.GetFiles(path)) File.Delete(p);
        foreach (string p in Directory.GetDirectories(path)) DeleteDir(p);
        Directory.Delete(path);
    }

19 Source : IOHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static void DeleteDirectory(string directory, bool delete = true)
        {
            if (!Directory.Exists(directory))
            {
                return;
            }
            var ds = Directory.GetDirectories(directory);
            foreach (var d in ds)
            {
                DeleteDirectory(d);
            }
            var fs = Directory.GetFiles(directory);
            foreach (var f in fs)
            {
                File.Delete(f);
            }
            if (delete)
            {
                Directory.Delete(directory);
            }
        }

19 Source : StickersExport.cs
with MIT License
from agens-no

public static void WriteToProject(string pathToBuiltProject)
        {
            var exists = Directory.Exists(pathToBuiltProject);
            if (!exists)
            {
                LogError("Could not find directory '" + pathToBuiltProject + "'");
                return;
            }

            var directories = Directory.GetDirectories(pathToBuiltProject);


            if (directories.Length == 0)
            {
                LogError("Could not find any directories in the directory '" + pathToBuiltProject + "'");
                return;
            }

            var pbxProjFile = directories.FirstOrDefault(file => Path.GetExtension(file) == ".pbxproj" || Path.GetExtension(file) == ".xcodeproj");
            if (pbxProjFile == null)
            {
                var files = Directory.GetFiles(pathToBuiltProject);
                if (files.Length == 0)
                {
                    LogError("Could not find any files in the directory '" + pathToBuiltProject + "'");
                    return;
                }

                pbxProjFile = files.FirstOrDefault(file => Path.GetExtension(file) == ".pbxproj" || Path.GetExtension(file) == ".xcodeproj");
                if (pbxProjFile == null)
                {
                    LogError("Could not find the Xcode project in the directory '" + pathToBuiltProject + "'");
                    return;
                }
            }

            var pack = EditorGUIUtility.Load(StickerreplacedetName) as StickerPack;
            AddSticker(pack);

#if UNITY_5_6_OR_NEWER
            var extensionBundleId = PlayerSettings.applicationIdentifier + "." + pack.BundleId;
#else
            var extensionBundleId = PlayerSettings.bundleIdentifier + "." + pack.BundleId;
#endif

            PBXProject.AddStickerExtensionToXcodeProject(
                ExportPath + ExportName + "/",
                pathToBuiltProject + "/",
                ExportName,
                extensionBundleId,
                PlayerSettings.iOS.appleDeveloperTeamID,
                PlayerSettings.bundleVersion,
                PlayerSettings.iOS.buildNumber,
                GetTargetDeviceFamily(PlayerSettings.iOS.targetDevice),
                pack.Signing.AutomaticSigning,
                pack.Signing.ProvisioningProfile,
                pack.Signing.ProvisioningProfileSpecifier
            );
            Log("Added sticker extension named " + pack.replacedle);
        }

19 Source : Program.cs
with The Unlicense
from AigioL

static void Main(string[] args)
        {
            TryMain();
            void TryMain()
            {
                try
                {
                    Main();
                }
                catch (Exception ex)
                {
                    var index = byte.MinValue;
                    while (ex != null)
                    {
                        if (index++ > sbyte.MaxValue) break;
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        ex = ex.InnerException;
                    }
                }
                Console.ReadLine();
            }
            void Main()
            {
                // ReSharper disable PossibleNullReferenceException
                var entryreplacedembly = replacedembly.GetEntryreplacedembly();
                var replacedle = entryreplacedembly.FullName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
                // ReSharper disable once replacedignNullToNotNullAttribute
                if (!replacedle.IsNullOrWhiteSpace()) Console.replacedle = replacedle;
                var rootPath = Path.GetDirectoryName(entryreplacedembly.Location);
                if (rootPath == null) throw new ArgumentNullException(nameof(rootPath));
                var sofilepath = args?.FirstOrDefault(x => x != null && File.Exists(x) && Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase));
                if (sofilepath == null)
                {
                    var sofilepaths = Directory.GetFiles(rootPath).Where(x => Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase)).ToArray();
                    sofilepath =
                       sofilepaths.FirstOrDefault(x => Path.GetFileName(x).Equals(GetSoDefaultFileName(), StringComparison.OrdinalIgnoreCase)) ??
                       sofilepaths.FirstOrDefault();
                }
                if (sofilepath == null) ReadLineAndExit("Can not find the .so file.");
                // ReSharper disable once replacedignNullToNotNullAttribute
                var bytes = File.ReadAllBytes(sofilepath);
                var elf = Elf.FromFile(sofilepath);
                var rodata = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".rodata"));
                if (rodata == null) ReadLineAndExit(".rodata not found.");
                var packedFiles = new List<string>();
                var addr = (uint)rodata.Addr;
                while (true)
                {
                    //up to 16 bytes of alignment
                    uint i;
                    for (i = 0; i < 16; i++)
                        if (bytes[addr + i] != 0)
                            break;

                    if (i == 16)
                        break; //We found all the files
                    addr += i;

                    var name = GetString(bytes, addr);
                    if (name.IsNullOrWhiteSpace())
                        break;

                    //We only care about dlls
                    if (!name.EndsWith(".dll"))
                        break;

                    packedFiles.Add(name);
                    addr += (uint)name.Length + 1u;
                }
                var data = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".data"));
                if (data == null) ReadLineAndExit(".data not found.");
                int ixGzip = 0;
                addr = (uint)data.Offset;
                var output = Path.Combine(rootPath, "replacedemblies");
                if (!Directory.Exists(output)) Directory.CreateDirectory(output);
                Console.WriteLine($"output:{output}");
                foreach (var item in packedFiles)
                {
                    ixGzip = findNextGZIPIndex(bytes, ixGzip);
                    if (ixGzip > 0)
                    {
                        var ptr = ixGzip;
                        var length = GetBigEndianUInt32(bytes, addr + 8);
                        var compressedbytes = new byte[length];
                        if (ptr + length <= bytes.LongLength)
                        {
                            Array.Copy(bytes, ptr, compressedbytes, 0, length);
                            try
                            {
                                var decompbytes = Decompress(compressedbytes);
                                var path = Path.Combine(output, item);
                                File.WriteAllBytes(path, decompbytes);
                                Console.WriteLine($"file:{item}");
                                addr += 0x10;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Failed to decompress file: {item} {e.Message}.");
                            }
                        }
                    }
                }
                TryOpenDir(output);
                // ReSharper restore PossibleNullReferenceException
            }
            void ReadLineAndExit(string writeLine = null)
            {
                if (writeLine != null) Console.WriteLine(writeLine);
                Console.ReadLine();
                Environment.Exit(0);
            }
            string GetSoFileExtension() => ".so";
            string GetSoDefaultFileName() => "libmonodroid_bundle_app" + GetSoFileExtension();
            string GetString(byte[] bytes, uint address)
            {
                int maxLength = 255;
                for (int i = (int)address; i < address + maxLength; i++)
                {
                    if (bytes[i] == 0)
                    {
                        maxLength = i - (int)address;
                        break;
                    }
                }
                var buffer = new byte[maxLength];
                Array.Copy(bytes, address, buffer, 0, maxLength);
                return Encoding.ASCII.GetString(buffer);
            }
            int findNextGZIPIndex(byte[] bytes, int ixGzip)
            {
                for (var j = ixGzip + 2; j < bytes.Length; j++)
                {
                    if (bytes[j - 1] == 0x1f && bytes[j] == 0x8b)
                    {
                        ixGzip = j - 1;
                        return ixGzip;
                    }
                }
                return 0;
            }
            byte[] Decompress(byte[] data)
            {
                using (var compressedStream = new MemoryStream(data))
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var resultStream = new MemoryStream())
                {
                    zipStream.CopyTo(resultStream);
                    return resultStream.ToArray();
                }
            }
            uint GetBigEndianUInt32(byte[] bytes, uint address)
            {
                var byte1 = (uint)bytes[(int)address + 3] << 24;
                var byte2 = (uint)bytes[(int)address + 2] << 16;
                var byte3 = (uint)bytes[(int)address + 1] << 8;
                var byte4 = bytes[(int)address];
                return byte1 + byte2 + byte3 + byte4;
            }
            void TryOpenDir(string dirpath)
            {
                try
                {
                    Process.Start(dirpath);
                }
                catch
                {
                    // ignored
                }
            }
        }

19 Source : DiskAccess.cs
with MIT License
from AiursoftWeb

public string[] GetAllFileNamesInHardware()
        {
            if (!Directory.Exists(_path))
            {
                Directory.CreateDirectory(_path);
            }
            return Directory.GetFiles(_path).Select(t => Path.GetFileNameWithoutExtension(t)).ToArray();
        }

19 Source : mainForm.cs
with MIT License
from ajohns6

public static void DeleteDirectory(string targetDir)
        {
            if (!Directory.Exists(targetDir)) return;

            File.SetAttributes(targetDir, FileAttributes.Normal);

            string[] files = Directory.GetFiles(targetDir);
            string[] dirs = Directory.GetDirectories(targetDir);

            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (string dir in dirs)
            {
                DeleteDirectory(dir);
            }

            Directory.Delete(targetDir, false);
        }

19 Source : TestDownloader.cs
with MIT License
from AkiniKites

protected override byte[] DownloadFile(string modelName)
        {
            var mode = 2;
            if (mode == 0)
            {
                var dl = File.ReadAllLines(@"debug\urls.txt");
                var url = dl[new Random((int)DateTime.Now.Ticks).Next(dl.Length)];
                var bytes = _client.DownloadData(url);
                return ApplyText(bytes, modelName);
            }
            if (mode == 1)
            {
                Thread.Sleep(1000);

                var files = Directory.GetFiles("debug\\img").ToList();
                var baseImg = files[new Random((int)DateTime.Now.Ticks).Next(files.Count)];

                var bytes = File.ReadAllBytes(baseImg);
                bytes = ApplyText(bytes, modelName);

                return bytes;
            }
            if (mode == 2)
            {
                var file = Path.Combine(@"E:\Projects\hzd-model-db-gen\db", modelName + ".jpg");
                var bytes = File.ReadAllBytes(file);

                return bytes;
            }

            return null;
        }

19 Source : FileBackup.cs
with MIT License
from AkiniKites

private static IEnumerable<string> GetMatchingFiles(string path)
        {
            var filename = Path.GetFileName(path);
            var matcher = new Regex($"^{Regex.Escape(filename)}{GuidPattern}$", RegexOptions.IgnoreCase);
            var dir = Path.GetDirectoryName(path);
            if (String.IsNullOrEmpty(dir))
                dir = ".";

            if (Directory.Exists(dir))
            {
                foreach (var file in Directory.GetFiles(dir))
                {
                    if (matcher.IsMatch(Path.GetFileName(file)))
                        yield return file;
                }
            }
        }

19 Source : Paths.cs
with MIT License
from AkiniKites

private static void DeleteDirectoryNoCheck(string path)
        {
            File.SetAttributes(path, FileAttributes.Normal);

            foreach (string file in Directory.GetFiles(path))
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (string dir in Directory.GetDirectories(path))
                DeleteDirectory(dir);

            Directory.Delete(path, false);
        }

19 Source : MagicLaboratory.cs
with MIT License
from alaabenfatma

public static string DeleteAllDirectoriesForce(string head, bool async = true)
        {
            if (DeletedFolders.Peek() == "End.")
                foreach (var file in Directory.GetFiles(head))
                    File.Delete(file);

            foreach (var h in Directory.GetDirectories(head))
                DeleteAllDirectoriesForce(h);

            Directory.Delete(head);
            return null;
        }

19 Source : SampleDbMigrationService.cs
with MIT License
from albyho

private string GetSolutionDirectoryPath()
        {
            var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());

            while (Directory.GetParent(currentDirectory.FullName) != null)
            {
                currentDirectory = Directory.GetParent(currentDirectory.FullName);

                if (Directory.GetFiles(currentDirectory.FullName).FirstOrDefault(f => f.EndsWith(".sln")) != null)
                {
                    return currentDirectory.FullName;
                }
            }

            return null;
        }

See More Examples