System.IO.File.ReadAllLines(string)

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

1569 Examples 7

19 Source : BotMainWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void getGamesFromFile()
        {
            string[] gameList = System.IO.File.ReadAllLines(gameListFile);
            foreach (string game in gameList)
            {
                listView1.Items.Add(new ListViewItem() { Content = game.Split('`')[1], Tag = game.Split('`')[0] });
            }
        }

19 Source : ToolWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void getGamesFromFile()
        {
            string[] gameList = System.IO.File.ReadAllLines(GAME_LIST_FILE);
            foreach (string game in gameList)
            {
                listView1.Items.Add(new ListViewItem() { Content = game.Split('`')[1], Tag = game.Split('`')[0] });
            }
        }

19 Source : Config.cs
with MIT License
from 0ffffffffh

public static Config Get()
        {
            string key, val;
            string[] optLines;

            string workDir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            if (!File.Exists(workDir + "\\.config"))
                return conf;

            if (conf != null)
                return conf;


            conf = new Config();

            optLines = File.ReadAllLines(workDir + "\\.config");

            if (optLines == null)
                return conf;

            foreach (var item in optLines)
            {
                var part = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (part != null && part.Length == 2)
                {
                    key = part[0].Trim();
                    val = part[1].Trim();

                    switch (key)
                    {
                        case "memcached_port":
                            conf.MemcachedPort = TryConv<int>(val, 11211);
                            break;
                        case "memcached_path":
                            conf.MemcachedPath = val;
                            break;
                        case "sbmon_path":
                            conf.SbmonPath = val;
                            break;
                        case "log_level":
                            conf.LogLevel = TryConv<int>(val, (int)LogType.Critical);
                            break;
                        case "dbpwd":
                            conf.DbPreplacedword = val;
                            break;
                        case "test_mode":
                            conf.TestMode = TryConv<bool>(val, true);
                            break;
                        case "html_replacedet_root":
                            conf.HtmlContentRoot = val;
                            break;
                        case "cacheset_salt":
                            conf.CacheSetSalt = val;
                            break;
                        case "records_per_page":
                            conf.RecordCountPerPage = TryConv<int>(val, 40);
                            break;
                        case "basliks_per_page":
                            conf.BaslikCountPerPage = TryConv<int>(val, 15);
                            break;
                    }
                }
            }
            
            optLines = null;

            return conf;
        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : ApplicationBuilderExtensions.cs
with MIT License
from 17MKH

public static IApplicationBuilder UseBanner(this IApplicationBuilder app, IHostApplicationLifetime appLifetime)
    {
        appLifetime.ApplicationStarted.Register(() =>
        {
            //显示启动Banner
            var customFile = Path.Combine(AppContext.BaseDirectory, "banner.txt");
            if (File.Exists(customFile))
            {
                try
                {
                    var lines = File.ReadAllLines(customFile);
                    foreach (var line in lines)
                    {
                        Console.WriteLine(line);
                    }
                }
                catch
                {
                    Console.WriteLine("banner.txt文件无效");
                }
            }
            else
            {
                ConsoleBanner();
            }
        });

        return app;
    }

19 Source : BeatmapConverter.cs
with MIT License
from 39M

static void Convert()
    {
        Debug.Log(string.Format("Source path: {0}", beatmapPath));

        // 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
        string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
        foreach (string directoryPath in sourceDirectories)
        {
            Music music = new Music();

            // 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
            string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
            int count = 0;
            foreach (string filepath in sourceFiles)
            {
                string[] lines = File.ReadAllLines(filepath);

                Beatmap beatmap = new Beatmap();
                music.beatmapList.Add(beatmap);

                #region Set Difficulty
                beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
                beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
                count++;
                #endregion

                #region Processing file line by line
                bool startProcessNotes = false;
                foreach (string line in lines)
                {
                    if (line.StartsWith("[HitObjects]"))
                    {
                        startProcessNotes = true;
                        continue;
                    }

                    if (!startProcessNotes)
                    {
                        // 处理谱面信息

                        int lastIndex = line.LastIndexOf(':');
                        if (lastIndex < 0)
                        {
                            // 如果不是有效信息行则跳过
                            continue;
                        }

                        string value = line.Substring(lastIndex + 1).Trim();

                        if (line.StartsWith("replacedle"))
                        {
                            music.replacedle = value;
                        }
                        else if (line.StartsWith("Artist"))
                        {
                            music.artist = value;
                        }
                        else if (line.StartsWith("AudioFilename"))
                        {
                            value = value.Remove(value.LastIndexOf('.'));
                            music.audioFilename = value;
                            music.bannerFilename = value;
                            music.soundEffectFilename = value;
                        }
                        else if (line.StartsWith("PreviewTime"))
                        {
                            music.previewTime = float.Parse(value) / 1000;
                        }
                        else if (line.StartsWith("Creator"))
                        {
                            beatmap.creator = value;
                        }
                        else if (line.StartsWith("Version"))
                        {
                            beatmap.version = value;
                        }
                    }
                    else
                    {
                        // 开始处理 HitObject

                        string[] noteInfo = line.Split(',');
                        int type = int.Parse(noteInfo[3]);

                        if ((type & 0x01) != 0)
                        {
                            // Circle
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Circle 相关的处理
                            });
                        }
                        else if ((type & 0x02) != 0)
                        {
                            // Slider
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Slider 相关的处理
                            });
                        }
                        else if ((type & 0x08) != 0)
                        {
                            // Spinner
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Spinner 相关的处理
                            });

                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[5]) / 1000,
                                // 其他 Spinner 相关的处理
                            });
                        }
                    }
                }
                #endregion
            }

            string targetPath = directoryPath + ".json";
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            File.WriteAllText(targetPath, music.ToJson());

            Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
        }

        Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
    }

19 Source : PlyHandler.cs
with MIT License
from 3DBear

public static PlyResult GetVerticesAndTriangles(string path)
        {
            List<string> header = File.ReadLines(path).TakeUntilIncluding(x => x == "end_header").ToList();
            var headerParsed = new PlyHeader(header);
            if (headerParsed.Format == PlyFormat.Ascii)
            {
                return ParseAscii(File.ReadAllLines(path).ToList(), headerParsed);
            }
            else if (headerParsed.Format == PlyFormat.BinaryLittleEndian)
            {
                return ParseBinaryLittleEndian(path, headerParsed);
            }
            else // todo: support BinaryBigEndian
            {
                return null;
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from 3RD-Dimension

private void Window_Drop(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

				if (files.Length > 0)
				{
					string file = files[0];

                     if (machine.Mode == Machine.OperatingMode.SendFile)
                    
						return;

						try
						{
							machine.SetFile(System.IO.File.ReadAllLines(file));
						}
						catch (Exception ex)
						{
							MessageBox.Show(ex.Message);
						}
				}
			}
		}

19 Source : MainWindow.xaml.FileTab.cs
with MIT License
from 3RD-Dimension

private void ReloadCurrentFile()
        {
            if (ReloadCurrentFileName == "")
                return;

            ToolPath = GCodeFile.Empty;

            try
            {
                machine.SetFile(System.IO.File.ReadAllLines(ReloadCurrentFileName));
                CurrentFileName = ReloadCurrentFileName;
            }
            catch (Exception ex)
            {
                Logger.Warn("Failed to reload file " + ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

19 Source : UnityARBuildPostprocessor.cs
with MIT License
from 734843327

static void UpdateDefinesInFile(string file, Dictionary<string, bool> valuesToUpdate)
	{
		string[] src = File.ReadAllLines(file);
		var copy = (string[])src.Clone();

		foreach (var kvp in valuesToUpdate)
			AddOrReplaceCppMacro(ref copy, kvp.Key, kvp.Value ? "1" : "0");

		if (!copy.SequenceEqual(src))
			File.WriteAllLines(file, copy);
	}

19 Source : KissManga.cs
with GNU General Public License v3.0
from 9vult

public override String[] GetDLChapters()
        {
            if (File.Exists(Path.Combine(mangaRoot.FullName, "cdl.txt")))
                return File.ReadAllLines(Path.Combine(mangaRoot.FullName, "cdl.txt"));
            else
                return null;
        }

19 Source : PointCloudToMeshComponent.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);


            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count == 0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " 8 0 1.1 0";//--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );

      
                //int maximumDeptOfReconstructionSurfaceTree = atoi(argv[4]);//8
                //int targetWidthOfTheFinestLevelOctree = atoi(argv[5]);//0
                //float ratioBetweenReconCubeAndBBCubeStd = atof(argv[6]);    // 1.1
                //bool ReconstructorUsingLinearInterpolation = atoi(argv[7]) == 1;//0


                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : PointCloudToMeshComponentFull.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            int maximumDeptOfReconstructionSurfaceTree = 8;
            int targetWidthOfTheFinestLevelOctree = 0;
            double ratioBetweenReconCubeAndBBCubeStd = 1.1;
            bool ReconstructorUsingLinearInterpolation = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);
            DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
            DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
            DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
            DA.GetData(7, ref ReconstructorUsingLinearInterpolation);

            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count==0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
                //--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );



                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware

public static void ReadIndexFromFile()
        {
            var location = replacedembly.GetExecutingreplacedembly().Location;

            var index = location.IndexOf(@"\bin", StringComparison.InvariantCulture);

            var filePath = location.Substring(0, index) + InvertedIndexRelativePath;

            string[] lines = File.ReadAllLines(filePath);

            _invertedIndex.Clear();
            foreach (var line in lines)
            {
                var splittedLine = line.Split('|');

                string term = splittedLine[0];
                var postings = splittedLine[1].Split(';');
                var termFrequencies = splittedLine[2].Split(',');
                var invertedDocFrequency = double.Parse(splittedLine[3]);

                var termInfos = new List<TermInfo>();

                for (int i = 0; i < postings.Length; i++)
                {
                    var posting = postings[i];
                    var tf = double.Parse(termFrequencies[i]);

                    var post = posting.Split(':');
                    var termEntries = post[1].Split(',').Select(ushort.Parse).ToArray();
                    
                    termInfos.Add(new TermInfo(new Guid(post[0]), termEntries, (float) tf));
                }

                _invertedIndex[term] = new Posting(termInfos) {InvertedDoreplacedentFrequency = invertedDocFrequency};
            }
        }

19 Source : LootParser.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static Dictionary<string, object> ParseFile(string filename)
        {
            var lines = File.ReadAllLines(filename);

            var tables = new Dictionary<string, object>();

            //Console.WriteLine($"Parsed {filename}");

            for (var i = 0; i < lines.Length; i++)
            {
                var line = lines[i];

                if (line.Contains("List<"))
                    continue;

                if (!line.Contains("ChanceTable<") || !line.Contains(" = new") || !line.Contains("()"))
                    continue;

                if (line.Contains("readonly") || line.EndsWith(";"))
                    continue;

                var table = ParseChanceTable(lines, i);

                tables.Add(table.tableName, table.table);
            }
            return tables;
        }

19 Source : Program_DbUpdates.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void PatchDatabase(string dbType, string host, uint port, string username, string preplacedword, string database)
        {
            var updatesPath = $"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}{dbType}";
            var updatesFile = $"{updatesPath}{Path.DirectorySeparatorChar}applied_updates.txt";
            var appliedUpdates = Array.Empty<string>();

            var containerUpdatesFile = $"/ace/Config/{dbType}_applied_updates.txt";
            if (IsRunningInContainer && File.Exists(containerUpdatesFile))
                File.Copy(containerUpdatesFile, updatesFile, true);

            if (File.Exists(updatesFile))
                appliedUpdates = File.ReadAllLines(updatesFile);

            Console.WriteLine($"Searching for {dbType} update SQL scripts .... ");
            foreach (var file in new DirectoryInfo(updatesPath).GetFiles("*.sql").OrderBy(f => f.Name))
            {
                if (appliedUpdates.Contains(file.Name))
                    continue;

                Console.Write($"Found {file.Name} .... ");
                var sqlDBFile = File.ReadAllText(file.FullName);
                var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={host};port={port};user={username};preplacedword={preplacedword};database={database};DefaultCommandTimeout=120");
                switch (dbType)
                {
                    case "Authentication":
                        sqlDBFile = sqlDBFile.Replace("ace_auth", database);
                        break;
                    case "Shard":
                        sqlDBFile = sqlDBFile.Replace("ace_shard", database);
                        break;
                    case "World":
                        sqlDBFile = sqlDBFile.Replace("ace_world", database);
                        break;
                }
                var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                Console.Write($"Importing into {database} database on SQL server at {host}:{port} .... ");
                try
                {
                    script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                    var count = script.Execute();
                    //Console.Write($" {count} database records affected ....");
                    Console.WriteLine(" complete!");
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    Console.WriteLine($" error!");
                    Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
                }
                File.AppendAllText(updatesFile, file.Name + Environment.NewLine);
            }

            if (IsRunningInContainer && File.Exists(updatesFile))
                File.Copy(updatesFile, containerUpdatesFile, true);

            Console.WriteLine($"{dbType} update SQL scripts import complete!");
        }

19 Source : DIDTables.cs
with GNU General Public License v3.0
from ACEmulator

public static void Load()
        {
            var filename = @"Data\DIDTables.txt";

            var lines = File.ReadAllLines(filename);

            for (var i = 0; i < lines.Length; i++)
            {
                var line = lines[i];

                // comment
                if (line.StartsWith("#"))
                    continue;

                var pieces = line.Split(',');

                if (pieces.Length != 4)
                {
                    Console.WriteLine($"DIDTables.Load({filename}): line {i + 1} length {pieces.Length}");
                    continue;
                }

                var setupID = pieces[0].Length > 0 ? Convert.ToUInt32(pieces[0], 16) : 0;
                var mtableID = pieces[1].Length > 0 ? Convert.ToUInt32(pieces[1], 16) : 0;
                var stableID = pieces[2].Length > 0 ? Convert.ToUInt32(pieces[2], 16) : 0;
                var ctableID = pieces[3].Length > 0 ? Convert.ToUInt32(pieces[3], 16) : 0;

                var table = new DIDTable(setupID);
                table.MotionTableID = mtableID;
                table.SoundTableID = stableID;
                table.CombatTableID = ctableID;

                Setups.Add(setupID, table);
            }
        }

19 Source : HatchEditor.cs
with GNU Lesser General Public License v3.0
from acnicholas

public static List<Hatch> ReadAllPatternsFromFile(string file)
        {
            if (File.Exists(file)) {
                var fileLines = File.ReadAllLines(file);
                return GetPatternFromFile(0, fileLines);
            } else {
                return new List<Hatch>();
            }
        }

19 Source : Program.cs
with MIT License
from actions

private static void LoadAndSetEnv()
        {
            var binDir = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            var rootDir = new DirectoryInfo(binDir).Parent.FullName;
            string envFile = Path.Combine(rootDir, ".env");
            if (File.Exists(envFile))
            {
                var envContents = File.ReadAllLines(envFile);
                foreach (var env in envContents)
                {
                    if (!string.IsNullOrEmpty(env))
                    {
                        var separatorIndex = env.IndexOf('=');
                        if (separatorIndex > 0)
                        {
                            string envKey = env.Substring(0, separatorIndex);
                            string envValue = null;
                            if (env.Length > separatorIndex + 1)
                            {
                                envValue = env.Substring(separatorIndex + 1);
                            }

                            Environment.SetEnvironmentVariable(envKey, envValue);
                        }
                    }
                }
            }
        }

19 Source : GitSourceProvider.cs
with MIT License
from actions

private async Task RemoveGitConfig(RunnerActionPluginExecutionContext executionContext, GitCliManager gitCommandManager, string targetPath, string configKey, string configValue)
        {
            int exitCode_configUnset = await gitCommandManager.GitConfigUnset(executionContext, targetPath, configKey);
            if (exitCode_configUnset != 0)
            {
                // if unable to use git.exe unset http.extraheader or core.askpreplaced, modify git config file on disk. make sure we don't left credential.
                if (!string.IsNullOrEmpty(configValue))
                {
                    executionContext.Warning("An unsuccessful attempt was made using git command line to remove \"http.extraheader\" from the git config. Attempting to modify the git config file directly to remove the credential.");
                    string gitConfig = Path.Combine(targetPath, ".git/config");
                    if (File.Exists(gitConfig))
                    {
                        List<string> safeGitConfig = new List<string>();
                        var gitConfigContents = File.ReadAllLines(gitConfig);
                        foreach (var line in gitConfigContents)
                        {
                            if (!line.Contains(configValue))
                            {
                                safeGitConfig.Add(line);
                            }
                        }

                        File.WriteAllLines(gitConfig, safeGitConfig);
                    }
                }
                else
                {
                    executionContext.Warning($"Unable to remove \"{configKey}\" from the git config. To remove the credential, execute \"git config --unset - all {configKey}\" from the repository root \"{targetPath}\".");
                }
            }
        }

19 Source : RunnerWebProxyL0.cs
with MIT License
from 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 Source : RunnerWebProxyL0.cs
with MIT License
from 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 Source : Program.cs
with MIT License
from adospace

public static void Main()
        {
            //force XF replacedembly load
            var _ = new Xamarin.Forms.Shapes.Rectangle();

            var types = (from domainreplacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
                             // alternative: from domainreplacedembly in domainreplacedembly.GetExportedTypes()
                         from replacedemblyType in domainreplacedembly.GetTypes()
                         where typeof(BindableObject).IsreplacedignableFrom(replacedemblyType)
                         // alternative: where replacedemblyType.IsSubclreplacedOf(typeof(B))
                         // alternative: && ! replacedemblyType.IsAbstract
                         select replacedemblyType)
                .ToDictionary(_ => _.FullName, _ => _);

            foreach (var clreplacedNameToGenerate in File.ReadAllLines("WidgetList.txt").Where(_ => !string.IsNullOrWhiteSpace(_)))
            {
                var typeToScaffold = types[clreplacedNameToGenerate];
                var outputPath = Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), "gen");
                Directory.CreateDirectory(outputPath);

                Scaffold(typeToScaffold, outputPath);
            }
        }

19 Source : AssetManager.cs
with MIT License
from Adsito

public static void SetVolumeGizmos()
    {
		if (File.Exists(VolumesListPath))
        {
			var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
			var cubeMesh = cube.GetComponent<MeshFilter>().sharedMesh;
			GameObject.DestroyImmediate(cube);
			var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
			var sphereMesh = sphere.GetComponent<MeshFilter>().sharedMesh;
			GameObject.DestroyImmediate(sphere);

			var volumes = File.ReadAllLines(VolumesListPath);
            for (int i = 0; i < volumes.Length; i++)
            {
				var lineSplit = volumes[i].Split(':');
				lineSplit[0] = lineSplit[0].Trim(' '); // Volume Mesh Type
				lineSplit[1] = lineSplit[1].Trim(' '); // Prefab Path
                switch (lineSplit[0])
                {
					case "Cube":
						LoadPrefab(lineSplit[1]).AddComponent<VolumeGizmo>().mesh = cubeMesh;
						break;
					case "Sphere":
						LoadPrefab(lineSplit[1]).AddComponent<VolumeGizmo>().mesh = sphereMesh;
						break;
                }
            }
        }
    }

19 Source : AssetManager.cs
with MIT License
from Adsito

public static IEnumerator SetMaterials(int materialID)
		{
			if (File.Exists(MaterialsListPath))
			{
				Shader std = Shader.Find("Standard");
				Shader spc = Shader.Find("Standard (Specular setup)");
				string[] materials = File.ReadAllLines(MaterialsListPath);
				for (int i = 0; i < materials.Length; i++)
				{
					var lineSplit = materials[i].Split(':');
					lineSplit[0] = lineSplit[0].Trim(' '); // Shader Name
					lineSplit[1] = lineSplit[1].Trim(' '); // Material Path
					Progress.Report(materialID, (float)i / materials.Length, "Setting: " + lineSplit[1]);
					switch (lineSplit[0])
					{
						case "Standard":
							Material matStd = Loadreplacedet<Material>(lineSplit[1]);
							if (matStd == null)
                            {
								Debug.LogWarning(lineSplit[1] + " is not a valid replacedet.");
								break;
                            }
							EditorCoroutineUtility.StartCoroutineOwnerless(UpdateShader(matStd, std));
							break;

						case "Specular":
							Material matSpc= Loadreplacedet<Material>(lineSplit[1]);
							if (matSpc == null)
							{
								Debug.LogWarning(lineSplit[1] + " is not a valid replacedet.");
								break;
							}
							EditorCoroutineUtility.StartCoroutineOwnerless(UpdateShader(matSpc, spc));
							break;

						case "Foliage":
							Material mat = Loadreplacedet<Material>(lineSplit[1]);
							if(mat == null)
                            {
								Debug.LogWarning(lineSplit[1] + " is not a valid replacedet.");
								break;
							}
							mat.DisableKeyword("_TINTENABLED_ON");
							break;

						default:
							Debug.LogWarning(lineSplit[0] + " is not a valid shader.");
							break;
					}
					yield return null;
				}
				Progress.Report(materialID, 0.99f, "Set " + materials.Length + " materials.");
				Progress.Finish(materialID, Progress.Status.Succeeded);
			}
		}

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

private void LoadNames()
        {
            string filePath = $"{Helper.DirectoryPath}/replacedets/names_female_{Config.LocaleString}.txt";
            if (File.Exists(filePath))
            {
                femaleNames = File.ReadAllLines(filePath);
                Monitor.Log($"Female names found at {filePath}.", LogLevel.Debug);
            }
            else
            {
                Monitor.Log($"Female names file not found at {filePath}.", LogLevel.Warn);
                femaleNames = new string[0];
            }
            filePath = $"{Helper.DirectoryPath}/replacedets/names_male_{Config.LocaleString}.txt";
            if (File.Exists(filePath))
            {
                maleNames = File.ReadAllLines(filePath);
                Monitor.Log($"Male names file found at {filePath}.", LogLevel.Debug);
            }
            else
            {
                Monitor.Log($"Male names file not found at {filePath}.", LogLevel.Warn);
                maleNames = new string[0];
            }

            if(Config.NeutralNameGender == "female")
            {
                neuterNames = femaleNames;

            }
            else if(Config.NeutralNameGender == "male")
            {
                neuterNames = maleNames;

            }
            else
            {
                filePath = $"{Helper.DirectoryPath}/replacedets/names_{Config.LocaleString}.txt";
                if (File.Exists(filePath))
                {
                    neuterNames = File.ReadAllLines(filePath);
                }
                else
                {
                    Monitor.Log($"Gender-neutral names file not found at {filePath}. Using combined male/female strings.", LogLevel.Debug);
                    neuterNames = new string[femaleNames.Length + maleNames.Length];
                    femaleNames.CopyTo(neuterNames, 0);
                    maleNames.CopyTo(neuterNames, femaleNames.Length);
                }
            }
        }

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

private void LoadQuotes()
        {
            string file = Path.Combine(Helper.DirectoryPath, "replacedets", "quotes.txt");
            if (!File.Exists(file))
            {
                Monitor.Log($"No quotes.txt file, using quotes_default.txt", LogLevel.Debug);
                file = Path.Combine(Helper.DirectoryPath, "replacedets", "quotes_default.txt");
            }
            if (File.Exists(file))
            {
                quotestrings = File.ReadAllLines(file);
                Monitor.Log($"Loaded {quotestrings.Length} quotes from {file}", LogLevel.Debug);
                foreach(string quote in quotestrings)
                {
                    if(quote.Length > 0)
                        quotes.Add(new Quote(quote));
                }
            }
            else
            {
                Monitor.Log($"Quotes file not found at {file}!", LogLevel.Error);
            }
        }

19 Source : CookieService.cs
with MIT License
from agc93

public Dictionary<string, string> GetCookies() {
            
            if (Path.HasExtension(_config.Cookies) && File.Exists(_config.Cookies)) {
                var ckTxt = File.ReadAllLines(Path.GetFullPath(_config.Cookies));
                var ckSet = ParseCookiesTxt(ckTxt);
                return ckSet;
            } else if (_config.Cookies.StartsWith("{") || _config.Cookies.StartsWith("%7B")) {
                //almost certainly a raw sid, we'll replacedume it is
                var raw = Uri.UnescapeDataString(_config.Cookies);
                return new Dictionary<string, string> {["sid"] = Uri.EscapeDataString(raw)};
            } else {
                if (_config.Cookies.Contains('\n')) {
                    var ckSet = ParseCookiesTxt(_config.Cookies.Split('\n'));
                    return ckSet;
                } else {
                    return _config.Cookies.Split(';').Select(s => s.Trim(' ')).ToDictionary(s => s.Split('=').First(), s => s.Split('=').Last());
                }
            }
            
        }

19 Source : IOManager.cs
with GNU General Public License v3.0
from AHeroicLlama

public static List<string> ReadPreferences()
		{
			try
			{
				if (File.Exists(settingsFileName))
				{
					return File.ReadAllLines(settingsFileName).ToList();
				}
				else
				{
					return null; // The prefs file did not exist
				}
			}
			catch (Exception e)
			{
				Notify.Error(
					"Mappalachia encountered an error while reading your user preferences file from " + settingsFileName + ". Your settings will be reset to default.\n" +
					genericExceptionHelpText +
					"\n\n" + e);

				return null;
			}
		}

19 Source : AisNetBenchmarks.cs
with GNU Affero General Public License v3.0
from ais-dotnet

[GlobalSetup]
        public void GlobalSetup()
        {
            // We have 1000 lines of real test data to provide a realistic mix of messages.
            // However, this is too small to get a good measurement of the per-message overhead,
            // because the per-execution overheads are a significant proportion of the whole at
            // that size.
            // For example, on an Intel Core i9-9900K CPU 3.60GHz, the InspectMessageType test
            // processes a 1000-message file in about 510us, suggesting a per-message cost of
            // about 510ns. However, if we run the exact same test against a 1,000,000 message
            // file, it takes about 340ms, suggesting a per-message cost of just 340ns. So by
            // measuring over 1,000 messages, we get a reading that's 50% higher than we do at
            // 1M. (We get similar results at 10M, so 1M seems to be sufficient. 100K might also
            // be enough, but it's easier to read the results when we multiple things up three
            // orders of magnitude at a time: it means that test times in ms correspond to
            // per-message times in ns.)
            string[] testFileLines = File.ReadAllLines(TestPath1kLines);
            using var f = new StreamWriter(TestPath1mLines);
            for (int i = 0; i < 1000; ++i)
            {
                foreach (string line in testFileLines)
                {
                    f.WriteLine(line);
                }
            }
        }

19 Source : SteamVR_ExternalCamera.cs
with MIT License
from ajayyy

public void ReadConfig()
	{
		try
		{
			var mCam = new HmdMatrix34_t();
			var readCamMatrix = false;

			object c = config; // box
			var lines = System.IO.File.ReadAllLines(configPath);
			foreach (var line in lines)
			{
				var split = line.Split('=');
				if (split.Length == 2)
				{
					var key = split[0];
					if (key == "m")
					{
						var values = split[1].Split(',');
						if (values.Length == 12)
						{
							mCam.m0 = float.Parse(values[0]);
							mCam.m1 = float.Parse(values[1]);
							mCam.m2 = float.Parse(values[2]);
							mCam.m3 = float.Parse(values[3]);
							mCam.m4 = float.Parse(values[4]);
							mCam.m5 = float.Parse(values[5]);
							mCam.m6 = float.Parse(values[6]);
							mCam.m7 = float.Parse(values[7]);
							mCam.m8 = float.Parse(values[8]);
							mCam.m9 = float.Parse(values[9]);
							mCam.m10 = float.Parse(values[10]);
							mCam.m11 = float.Parse(values[11]);
							readCamMatrix = true;
						}
					}
#if !UNITY_METRO
					else if (key == "disableStandardreplacedets")
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, bool.Parse(split[1]));
					}
					else
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, float.Parse(split[1]));
					}
#endif
				}
			}
			config = (Config)c; //unbox

			// Convert calibrated camera matrix settings.
			if (readCamMatrix)
			{
				var t = new SteamVR_Utils.RigidTransform(mCam);
				config.x = t.pos.x;
				config.y = t.pos.y;
				config.z = t.pos.z;
				var angles = t.rot.eulerAngles;
				config.rx = angles.x;
				config.ry = angles.y;
				config.rz = angles.z;
			}
		}
		catch { }

		// Clear target so AttachToCamera gets called to pick up any changes.
		target = null;
#if !UNITY_METRO
		// Listen for changes.
		if (watcher == null)
		{
			var fi = new System.IO.FileInfo(configPath);
			watcher = new System.IO.FileSystemWatcher(fi.DirectoryName, fi.Name);
			watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
			watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged);
			watcher.EnableRaisingEvents = true;
		}
	}

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 : Program.cs
with MIT License
from Alan-FGR

static void Main(string[] args)
    {
        String[] files = {"Registry", "ArchetypePool"};
        string path = "Archetypes";

        Console.WriteLine("C# VARIADIC GENERATOR. VALID TAGS:");
        foreach (var modeFunction in modeFunctions)
        {
            Console.WriteLine($"  {modeFunction.Key}");
            Console.WriteLine($"    Description: {modeFunction.Value.descr}");
        }

        foreach (string file in Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories))
        {
            var pathElements = file.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
            if (pathElements.Contains("obj"))
                continue;
            if (!files.Contains(Path.GetFileName(file)) && !files.Contains(Path.GetFileNameWithoutExtension(file)))
                continue;
            
            var code = File.ReadAllLines(file);
            var generatedCode = new StringWriter();

            Console.WriteLine($"PARSING FILE: {file}...");

            var regions = new List<(int qty, List<string> lines)>();

            List<string> currentRegion = null;

            foreach (string line in code)
            {
                if (line.ToLowerInvariant().Contains("#region variadic"))
                {
                    currentRegion = new List<string>();
                    regions.Add((int.Parse(line.Trim().Split(' ')[2]), currentRegion));
                    continue;
                }

                if (line.ToLowerInvariant().Contains("#endregion"))
                {
                    currentRegion = null;
                    continue;
                }

                currentRegion?.Add(line);
            }

            foreach (var tuple in regions)
            {
                curRegion = tuple.lines;
                for (int qti = 2; qti <= tuple.qty; qti++)
                {
                    curQty = qti;
                    for (var i = 0; i < tuple.lines.Count; i++)
                    {
                        string line = tuple.lines[i];

                        var trimmed = line.TrimStart(' ');
                        if (trimmed.Length >= 2)
                        {
                            string substring = trimmed.Substring(0, 2);
                            if (substring == "//")
                                continue;
                            if (substring == "/*")
                                Console.WriteLine($"MULTILINE COMMENT BLOCKS (DETECTED ON LINE {i}) NOT SUPPORTED." +
                                                  "YOU CAN USE THEM FOR COMMENTS AS USUAL BUT MAKE SURE THERE ARE NO TAGS IN THEM.");
                        }

                        if (line.ToLowerInvariant().Contains("genvariadic"))
                        {
                            var pars = line.Split("genvariadic")[1].Split(' ', StringSplitOptions.RemoveEmptyEntries);
                            Console.WriteLine(
                                $"found variadic on line {i}, {pars.Length} parameters: {string.Join(", ", pars)}");

                            if (pars.Length < 1)
                            {
                                Console.WriteLine("NO PARAMETERS!");
                                continue;
                            }

                            var mode = pars.First();
                            var options = pars.Skip(1).ToArray();

                            if (modeFunctions.TryGetValue(mode, out var value))
                            {
                                var str = value.Item2(options, i);
                                generatedCode.WriteLine(str);
                            }
                            else
                            {
                                string err = $"INVALID MODE: {mode}";
                                Console.WriteLine(err);
                                generatedCode.WriteLine(err);
                            }
                        }
                        else
                        {
                            generatedCode.WriteLine(line);
                        }
                    }
                }
            }

            Console.WriteLine($"PARSED FILE: {file}\n");


            var allcode = "";
            foreach (string line in code)
            {
                var trimmed = (line.Trim());
                if (trimmed.Length > 6)
                    if (trimmed.Substring(0, 5) == "using")
                        allcode += line+"\r\n";
            }

            allcode += $"public unsafe partial clreplaced {Path.GetFileNameWithoutExtension(file)} {{";

            allcode += generatedCode.ToString();

            allcode += "}";

            File.WriteAllText(Path.Combine(path, Path.GetFileNameWithoutExtension(file)+"GeneratedVariadic.cs"), allcode);

        }

        //Console.ReadKey();
    }

19 Source : LSPDFRPlusHandler.cs
with GNU General Public License v3.0
from Albo1125

public static void Initialise()
        {
            //ini stuff

            InitializationFile ini = new InitializationFile("Plugins/LSPDFR/LSPDFR+.ini");
            ini.Create();
            try
            {
                EnhancedTrafficStop.BringUpTrafficStopMenuControllerButton = ini.ReadEnum<ControllerButtons>("General", "BringUpTrafficStopMenuControllerButton", ControllerButtons.DPadRight);
                EnhancedTrafficStop.BringUpTrafficStopMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "BringUpTrafficStopMenuKey", "D7"));
              
                try
                {
                    stockLSPDFRIni = new InitializationFile(LSPDFRKeyIniPath);
                    string[] stockinicontents = File.ReadAllLines(LSPDFRKeyIniPath);
                    //Alternative INI reading implementation, RPH doesn't work with sectionless INIs.
                    foreach (string line in stockinicontents)
                    {
                        if (line.StartsWith("TRAFFICSTOP_INTERACT_Key="))
                        {
                            stockTrafficStopInteractKey = (Keys)kc.ConvertFromString(line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ModifierKey"))
                        {
                            stockTrafficStopInteractModifierKey = (Keys)kc.ConvertFromString(line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ControllerKey"))
                        {
                            stockTrafficStopInteractControllerButton = (ControllerButtons)Enum.Parse(typeof(ControllerButtons), line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ControllerModifierKey"))
                        {
                            stockTrafficStopInteractModifierControllerButton = (ControllerButtons)Enum.Parse(typeof(ControllerButtons), line.Substring(line.IndexOf('=') + 1));
                        }
                    }
                    if ((EnhancedTrafficStop.BringUpTrafficStopMenuKey == stockTrafficStopInteractKey && stockTrafficStopInteractModifierKey == Keys.None) || (EnhancedTrafficStop.BringUpTrafficStopMenuControllerButton == stockTrafficStopInteractControllerButton && stockTrafficStopInteractModifierControllerButton == ControllerButtons.None))
                    {
                        TrafficStopMenuPopup = new Popup("LSPDFR+: Traffic Stop Menu Conflict", "Your LSPDFR+ traffic stop menu keys (plugins/lspdfr/lspdfr+.ini) are the same as the default LSPDFR traffic stop keys (lspdfr/keys.ini TRAFFICSTOP_INTERACT_Key and TRAFFICSTOP_INTERACT_ControllerKey). How would you like to solve this?",
                            new List<string>() { "Recommended: Automatically disable the default LSPDFR traffic stop menu keys (this will edit keys.ini TRAFFICSTOP_INTERACT_Key and TRAFFICSTOP_INTERACT_ControllerKey to None)", "I know what I'm doing, I will change the keys in the INIs myself!" }, false, true, TrafficStopMenuCb);
                        TrafficStopMenuPopup.Display();
                    }
                }
                catch (Exception e)
                {
                    Game.LogTrivial($"Failed to determine stock LSPDFR key bind/controller button for traffic stop keys: {e}");
                }
              
                CourtSystem.OpenCourtMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("OnlyWithoutBritishPolicingScriptInstalled", "OpenCourtMenuKey", "F9"));
                CourtSystem.OpenCourtMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("OnlyWithoutBritishPolicingScriptInstalled", "OpenCourtMenuModifierKey", "None"));
                EnhancedTrafficStop.EnhancedTrafficStopsEnabled = ini.ReadBoolean("General", "EnhancedTrafficStopsEnabled", true);
                EnhancedPursuitAI.EnhancedPursuitAIEnabled = ini.ReadBoolean("General", "EnhancedPursuitAIEnabled", true);
                EnhancedPursuitAI.AutoPursuitBackupEnabled = ini.ReadBoolean("General", "AutoPursuitBackupEnabled", false);
                EnhancedPursuitAI.OpenPursuitTacticsMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenPursuitTacticsMenuKey", "Q"));
                EnhancedPursuitAI.OpenPursuitTacticsMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenPursuitTacticsMenuModifierKey", "LShiftKey"));
                EnhancedPursuitAI.DefaultAutomaticAI = ini.ReadBoolean("General", "DefaultAutomaticAI", true);

                Offence.maxpoints = ini.ReadInt32("General", "MaxPoints", 12);
                Offence.pointincstep = ini.ReadInt32("General", "PointsIncrementalStep", 1);
                Offence.maxFine = ini.ReadInt32("General", "MaxFine", 5000);

                Offence.OpenTicketMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenTicketMenuKey", "Q"));
                Offence.OpenTicketMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenTicketMenuModifierKey", "LShiftKey"));
                Offence.enablePoints = ini.ReadBoolean("General", "EnablePoints", true);

                CourtSystem.RealisticCourtDates = ini.ReadBoolean("OnlyWithoutBritishPolicingScriptInstalled", "RealisticCourtDates", true);
            }
            catch (Exception e)
            {
                Game.LogTrivial(e.ToString());
                Game.LogTrivial("Error loading LSPDFR+ INI file. Loading defaults");
                Game.DisplayNotification("~r~Error loading LSPDFR+ INI file. Loading defaults");
            }
            BetaCheck();
        }

19 Source : LSPDFRPlusHandler.cs
with GNU General Public License v3.0
from Albo1125

private static void TrafficStopMenuCb(Popup p)
        {
            if (p.IndexOfGivenAnswer == 0)
            {
                GameFiber.StartNew(delegate
                {
                    //RPH ini implementation does not work with INIs without sections!
                    string[] stockinicontents = File.ReadAllLines(LSPDFRKeyIniPath);
                    using (StreamWriter writer = new StreamWriter(LSPDFRKeyIniPath))
                    {
                        foreach (string line in stockinicontents)
                        {

                            if (line.StartsWith("TRAFFICSTOP_INTERACT_Key") && EnhancedTrafficStop.BringUpTrafficStopMenuKey == stockTrafficStopInteractKey && stockTrafficStopInteractModifierKey == Keys.None)
                            {
                                writer.WriteLine("TRAFFICSTOP_INTERACT_Key=None");
                            }
                            else if (line.StartsWith("TRAFFICSTOP_INTERACT_ControllerKey") && EnhancedTrafficStop.BringUpTrafficStopMenuControllerButton == stockTrafficStopInteractControllerButton && stockTrafficStopInteractModifierControllerButton == ControllerButtons.None)
                            {
                                writer.WriteLine("TRAFFICSTOP_INTERACT_ControllerKey=None");
                            }
                            else
                            {
                                writer.WriteLine(line);
                            }
                        }
                    }
                    Game.DisplayNotification("The default LSPDFR traffic stop menu keys have been disabled (INI changed to None). LSPDFR will now reload, type ~b~forceduty~w~ in the console to resume play.");
                    GameFiber.Wait(3000);
                    Game.ReloadActivePlugin();
                    
                });
            }
            else if (p.IndexOfGivenAnswer == 1)
            {
                Game.DisplayNotification("Your ~g~LSPDFR+ Traffic Stop~w~ menu key/controller button is still the same as for the default LSPDFR Traffic Stop. This will cause ~r~problems~w~, ensure you change it!");
            }
        }

19 Source : PackageChecker.cs
with MIT License
from alelievr

[InitializeOnLoadMethod]
        static void CheckPackage()
        {
            string filePath = Application.dataPath + "/../Library/PackageChecked";

 
            packageToAdd = new List<PackageEntry>();
            listRequest = null;

             
            if (!File.Exists(filePath))
            {
                var packageListFile = Directory.GetFiles(Application.dataPath, "PackageImportList.txt", SearchOption.AllDirectories);
                if (packageListFile.Length == 0)
                {
                    Debug.LogError("[Auto Package] : Couldn't find the packages list. Be sure there is a file called PackageImportList in your project");
                }
                else
                {
                    string packageListPath = packageListFile[0];
                    packageToAdd = new List<PackageEntry>();
                    string[] content = File.ReadAllLines(packageListPath);
                    foreach (var line in content)
                    {
                        var split = line.Split('@');
                        PackageEntry entry = new PackageEntry();

                        entry.name = split[0];
                        entry.version = split.Length > 1 ? split[1] : null;

                        packageToAdd.Add(entry);
                    }

                    File.WriteAllText(filePath, "Delete this to trigger a new auto package check");

                    listRequest = Client.List();

                    while (!listRequest.IsCompleted)
                    {
                        if (listRequest.Status == StatusCode.Failure || listRequest.Error != null)
                        {
                            Debug.LogError(listRequest.Error.message);
                            break;
                        }
                    }

                    addRequests = new AddRequest[packageToAdd.Count];

                    installRequired = new bool[packageToAdd.Count];

                    for (int i = 0; i < installRequired.Length; i++)
                        installRequired[i] = true;

                     
                    
                    foreach (var package in listRequest.Result)
                    {
                        for (int i = 0; i < packageToAdd.Count; i++)
                        {
                            if (package.packageId.Contains(packageToAdd[i].name))
                            {
                                installRequired[i] = false;

                                if (package.versions.latestCompatible != "" && package.version != "")
                                {

                                    if (GreaterThan(package.versions.latestCompatible, package.version))
                                    {
                                        installRequired[i] = EditorUtility.DisplayDialog("Confirm Package Upgrade", string.Format("The version of \"{0}\" in this project is not the latest version. Would you like to upgrade it to the latest version? (Recommmended)", packageToAdd[i].name), "Yes", "No");

                                        if (installRequired[i])
                                            packageToAdd[i].version = package.versions.latestCompatible;

                                    }
                                }
                            }
                        }

                    }
                

                    for (int i = 0; i < packageToAdd.Count; i++)
                    {
                        if (installRequired[i])
                            addRequests[i] = InstallSelectedPackage(packageToAdd[i].name, packageToAdd[i].version);
                    }


                    
                    ReimportPackagesByKeyword();


                }
            }
        }

19 Source : GraphCLI.Generator.cs
with MIT License
from alelievr

public static void Import(BaseGraph graph, string filePath, bool wipeDatas = false)
		{
			if (wipeDatas)
			{
				while (graph.nodes.Count != 0)
				{
					Debug.Log("removing node: " + graph.nodes.First());
					graph.RemoveNode(graph.nodes.First());
				}
			}

			string[] commands = File.ReadAllLines(filePath);
			foreach (var command in commands)
			{
				//ignore empty lines:
				if (String.IsNullOrEmpty(command.Trim()))
					continue ;
				
				Execute(graph, command);
			}
		}

19 Source : CubeLutAssetImporter.cs
with MIT License
from alelievr

static void ImportCubeLut(string path)
        {
            // Remove the 'replacedets' part of the path & build absolute path
            string fullpath = path.Substring(7);
            fullpath = Path.Combine(Application.dataPath, fullpath);

            // Read the lut data
            string[] lines = File.ReadAllLines(fullpath);

            // Start parsing
            int i = 0;
            int size = -1;
            int sizeCube = -1;
            var table = new List<Color>();
            var domainMin = Color.black;
            var domainMax = Color.white;

            while (true)
            {
                if (i >= lines.Length)
                {
                    if (table.Count != sizeCube)
                        Debug.LogError("Premature end of file");

                    break;
                }

                string line = FilterLine(lines[i]);

                if (string.IsNullOrEmpty(line))
                    goto next;

                // Header data
                if (line.StartsWith("replacedLE"))
                    goto next; // Skip the replacedle tag, we don't need it

                if (line.StartsWith("LUT_3D_SIZE"))
                {
                    string sizeStr = line.Substring(11).TrimStart();

                    if (!int.TryParse(sizeStr, out size))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    if (size < 2 || size > 256)
                    {
                        Debug.LogError("LUT size out of range");
                        break;
                    }

                    sizeCube = size * size * size;
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MIN"))
                {
                    if (!ParseDomain(i, line, ref domainMin)) break;
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MAX"))
                {
                    if (!ParseDomain(i, line, ref domainMax)) break;
                    goto next;
                }

                // Table
                string[] row = line.Split();

                if (row.Length != 3)
                {
                    Debug.LogError("Invalid data on line " + i);
                    break;
                }

                var color = Color.black;
                for (int j = 0; j < 3; j++)
                {
                    float d;
                    if (!float.TryParse(row[j], out d))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    color[j] = d;
                }

                table.Add(color);

            next:
                i++;
            }

            if (sizeCube != table.Count)
            {
                Debug.LogError("Wrong table size - Expected " + sizeCube + " elements, got " + table.Count);
                return;
            }

            // Check if the Texture3D already exists, update it in this case (better workflow for
            // the user)
            string replacedetPath = Path.ChangeExtension(path, ".replacedet");
            var tex = replacedetDatabase.LoadreplacedetAtPath<Texture3D>(replacedetPath);

            if (tex != null)
            {
                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();
            }
            else
            {
                // Generate a new Texture3D
                tex = new Texture3D(size, size, size, TextureFormat.RGBAHalf, false)
                {
                    anisoLevel = 0,
                    filterMode = FilterMode.Bilinear,
                    wrapMode = TextureWrapMode.Clamp,
                };

                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();

                // Save to disk
                replacedetDatabase.Createreplacedet(tex, replacedetPath);
            }

            replacedetDatabase.Savereplacedets();
            replacedetDatabase.Refresh();
        }

19 Source : GraphImportExportTests.cs
with MIT License
from alelievr

[Test]
		static public void BaseGraphExport()
		{
			var graph = TestUtils.GenerateTestWorldGraph();

			graph.Export(tmpFilePath);

			string[] lines = File.ReadAllLines(tmpFilePath);

			foreach (var line in lines)
				BaseGraphCLI.Parse(line);
		}

19 Source : GraphBuilder.cs
with MIT License
from alelievr

public GraphBuilder Import(string fileName, bool replacedetPath = true)
		{
			string filePath = fileName;

			if (replacedetPath)
			{
				#if UNITY_EDITOR
					filePath = Path.Combine(Application.dataPath, fileName);
				#else
					filePath = Path.Combine(Application.persistentDataPath, fileName);
				#endif
			}
			string[] lines = File.ReadAllLines(filePath);

			foreach (var line in lines)
				commands.Add(line);

			return this;
		}

19 Source : App.cs
with MIT License
from alexanderdna

public ConnectPeersResult ConnectToPeers()
        {
            var peersFile = PathsProvider.Peers;
            if (File.Exists(peersFile) is false)
            {
                Logger.Log(LogLevel.Warning, "Cannot find peers file.");
                return ConnectPeersResult.NoPeersFile;
            }

            List<(IPAddress, int)> addresses = new();
            try
            {
                var lines = File.ReadAllLines(peersFile);
                for (int i = 0, c = lines.Length; i < c; ++i)
                {
                    if (lines[i] == "") continue;

                    int posOfColon = lines[i].LastIndexOf(':');
                    if (posOfColon < 0)
                    {
                        Logger.Log(LogLevel.Warning, "Peers file seems to have invalid addresses.");
                        continue;
                    }

                    var host = IPAddress.Parse(lines[i].Substring(0, posOfColon));
                    var port = int.Parse(lines[i].Substring(posOfColon + 1));
                    if (port <= 0 || port > 65535)
                    {
                        Logger.Log(LogLevel.Warning, "Peers file seems to have invalid addresses.");
                        continue;
                    }

                    addresses.Add((host, port));
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Error, "Cannot connect to peers: " + ex.Message);
                return ConnectPeersResult.Failure;
            }

            return Daemon.AcceptPeerList(addresses) ? ConnectPeersResult.Success : ConnectPeersResult.Failure;
        }

19 Source : Parser.Internal.cs
with MIT License
from AlexGhiondea

private static string[] ExpandResponseFiles(string[] args)
        {
            // let's do a quick preplaced and see if any of the args start with @

            bool shouldExpand = false;
            for (int i = 0; i < args.Length; i++)
            {
                // it might be possible that the args[i] value is an empty string.
                // we should check and make sure we have a valid value here before trying to check the '@' char
                if (!string.IsNullOrEmpty(args[i]) && args[i][0] == '@')
                {
                    shouldExpand = true;
                    break;
                }
            }

            if (!shouldExpand)
                return args;

            // we need to expand the response files
            List<string> newArgs = new List<string>();

            for (int i = 0; i < args.Length; i++)
            {
                if (!string.IsNullOrEmpty(args[i]) && args[i][0] == '@')
                {
                    string fileName = args[i].Substring(1);
                    // does the file exist?
                    if (!File.Exists(fileName))
                    {
                        throw new FileNotFoundException($"Could not find response file [Yellow!{args[i]}]");
                    }

                    foreach (var line in File.ReadAllLines(fileName))
                    {
                        // we need to parse the line into a list of strings.
                        // we are going to split the line on space (except if we have just seen a ")
                        newArgs.AddRange(SplitCommandLineIntoSegments(line));
                    }
                }
                else
                {
                    newArgs.Add(args[i]);
                }
            }

            return newArgs.ToArray();
        }

19 Source : FixClassName.cs
with MIT License
from alexjhetherington

private static void replaceClreplacedName(string clreplacedName, string scriptPath)
        {
            try
            {
                String[] fileText = File.ReadAllLines(scriptPath);

                for (int i = 0; i < fileText.Length; i++)
                {
                    // make the refactoring only if the clreplaced name is different
                    if (Regex.IsMatch(fileText[i], @"\bclreplaced\b"))
                    {
                        if (Regex.IsMatch(fileText[i], "\\b" + clreplacedName + "\\b"))
                        {
                            Debug.Log(noRefactoringMessage);
                            return; // skip if the name is the same
                        }

                        // match the identifier of a clreplaced so it can be replaced by 'clreplacedName'
                        // we use a Positive Lookbehind...
                        String regexPattern = @"(?<=clreplaced )\w+";
                        fileText[i] = Regex.Replace(fileText[i], regexPattern, clreplacedName);
                        File.WriteAllLines(scriptPath, fileText);

                        Debug.Log(refactoringMessage);
                    }
                    else if (Regex.IsMatch(fileText[i], @"\binterface\b"))
                    {
                        if (Regex.IsMatch(fileText[i], "\\b" + clreplacedName + "\\b"))
                        {
                            Debug.Log(noRefactoringMessage);
                            return; // skip if the name is the same
                        }

                        // match the identifier of a clreplaced so it can be replaced by 'clreplacedName'
                        // we use a Positive Lookbehind...
                        String regexPattern = @"(?<=interface )\w+";
                        fileText[i] = Regex.Replace(fileText[i], regexPattern, clreplacedName);
                        File.WriteAllLines(scriptPath, fileText);

                        Debug.Log(refactoringMessage);
                    }
                }
            }
            catch (Exception exc) { Debug.Log(String.Format(errorMessage, exc.Message)); }
        }

19 Source : IDMigrationEditor.cs
with MIT License
from AlFasGD

public void LoadIDMigrationSteps(string fileName)
        {
            CurrentlySelectedIDMigrationSteps = LoadRangesFromStringArray(File.ReadAllLines(fileName));
            IDMigrationInfo.CurrentlySelectedIDMigrationModeInfo.FileName = fileName;
        }

19 Source : main.cs
with GNU General Public License v3.0
from ALIILAPRO

private void btnloadproxy_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Text File (*.txt)|*.txt|All File (*.*)|*.*";
            openFileDialog.replacedle = "Open Proxylist ( ONLY HTTP-S )";
            this.ProxyList.Clear();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.ProxyList.AddRange(File.ReadAllLines(openFileDialog.FileName));
                this.lblproxy.Text = this.ProxyList.Count.ToString();
            }
        }

19 Source : Splitting.cs
with MIT License
from Alkl58

private static void FFmpegSceneDetect()
        {
            // Skip Scene Detect if the file already exist
            if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")) == false)
            {
                Helpers.Logging("Scene Detection with FFmpeg");

                List<string> scenes = new List<string>();

                // Starts FFmpeg Process
                Process FFmpegSceneDetect = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WorkingDirectory = Global.FFmpeg_Path,
                    RedirectStandardError = true,
                    FileName = "cmd.exe",
                    Arguments = "/C ffmpeg.exe -i " + '\u0022' + Global.Video_Path + '\u0022' + " -hide_banner -loglevel 32 -filter_complex select=" + '\u0022' + "gt(scene\\," + FFmpeg_Threshold + "),select=eq(key\\,1),showinfo" + '\u0022' + " -an -f null -"
                };
                FFmpegSceneDetect.StartInfo = startInfo;
                FFmpegSceneDetect.Start();

                // Reads Standard Err from FFmpeg Output
                string stream = FFmpegSceneDetect.StandardError.ReadToEnd();

                FFmpegSceneDetect.WaitForExit();

                // Splits the Console Output by spaces
                string[] array = stream.Split(' ');

                // Searches for pts_time, if found it removes "pts_time:" to get only values
                foreach (string value in array) { if (value.Contains("pts_time:")) { scenes.Add(value.Remove(0, 9)); } }

                // Temporary value for Arg creation
                string previousScene = "0.000";

                // Clears the Args List to avoid conflicts in Batch Encode Mode
                FFmpegArgs.Clear();

                // Creates the seeking args for ffmpeg piping
                foreach (string sc in scenes)
                {
                    FFmpegArgs.Add("-ss " + previousScene + " -to " + sc);
                    previousScene = sc;
                }
                // Argument for seeking until the end of the video
                FFmpegArgs.Add("-ss " + previousScene);

                // Writes splitting arguments to text file
                foreach (string line in FFmpegArgs)
                {
                    using (StreamWriter sw = File.AppendText(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
                    {
                        sw.WriteLine(line);
                        sw.Close();
                    }
                }

                if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
                {
                    Global.Video_Chunks = File.ReadAllLines(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")); // Reads the split file for VideoEncode() function
                }
            }
        }

19 Source : Splitting.cs
with MIT License
from Alkl58

private static void PySceneDetectParse()
        {
            // Reads first line of the csv file generated by pyscenedetect
            string line = File.ReadLines(Path.Combine(Global.temp_path, Global.temp_path_folder, Global.temp_path_folder + "-Scenes.csv")).First();

            // Splits the line after "," and skips the first line, then adds the result to list
            List<string> scenes = line.Split(',').Skip(1).ToList<string>();

            // Temporary value used for creating the ffmpeg command line
            string previousScene = "00:00:00.000";

            // Clears the Args List to avoid conflicts in Batch Encode Mode
            FFmpegArgs.Clear();

            // Iterates over the list of time codes and creates the args for ffmpeg
            foreach (string sc in scenes)
            {
                FFmpegArgs.Add("-ss " + previousScene + " -to " + sc);
                previousScene = sc;
            }

            // Has to be last, to "tell" ffmpeg to seek / encode until end of video
            FFmpegArgs.Add("-ss " + previousScene);

            // Writes splitting arguments to text file
            foreach (string lineArg in FFmpegArgs)
            {
                using (StreamWriter sw = File.AppendText(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
                {
                    sw.WriteLine(lineArg);
                    sw.Close();
                }
            }

            if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
            {
                Global.Video_Chunks = File.ReadAllLines(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")); // Reads the split file for VideoEncode() function
            }
        }

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static string[] LoadDataFromFile (string path) {
			string[] data = File.ReadAllLines(path);
			return data;
		}

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static string[] ReadFile (string path) {
			string[] data = File.ReadAllLines(path);
			return data;
		}

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static List<string> LoadDataListFromFile (string path) {
			List<string> data = new List<string>(File.ReadAllLines(path));
			return data;
		}

See More Examples