private static void ReadStudentsInfoFromFile(string filePath, SortedDictionary<string, SortedSet<Student>> courses) { using (StreamReader reader = new StreamReader(filePath)) { string line = reader.ReadLine(); while (line != string.Empty && line != null) { string[] data = line.Split('|'); string firstName = data[0].Trim(); string lastName = data[1].Trim(); string courseName = data[2].Trim(); if (courses.ContainsKey(courseName)) { courses[courseName].Add(new Student(firstName, lastName)); } else { courses[courseName] = new SortedSet<Student>(); courses[courseName].Add(new Student(firstName, lastName)); } line = reader.ReadLine(); } } }
/// Read long numbers and initialize parameters /// A0 - The right particle of the first part of the number /// A1 - The left particle of the first part of the number /// B0 - The right particle of the second part of the number /// B1 - The left particle of the second part of the number /// K - Middle of the numbers /// N - Number of bits public static void Read(out BigInteger A0, out BigInteger A1, out BigInteger B0, out BigInteger B1, out int K, out int N) { using (StreamReader sr = new StreamReader("test.txt")) { string a, a0, a1, b, b0, b1; a = sr.ReadLine(); b = sr.ReadLine(); K = a.Length / 2; N = a.Length; // making strings to parse a0 = a.Substring(0, K); a1 = a.Substring(K); b0 = b.Substring(0, K); b1 = b.Substring(K); A0 = BigInteger.Parse(a1); A1 = BigInteger.Parse(a0); B0 = BigInteger.Parse(b1); B1 = BigInteger.Parse(b0); } }
public BoxInfo(int clientID, string fileName) { StreamReader sr = new StreamReader(fileName); sr.ReadLine();// burn the headings for (int x = 0; x < 28; x++) { myCompartments[x] = new Compartment(); } string[] dataLine; while (!sr.EndOfStream) { dataLine = sr.ReadLine().Split(','); int curID = int.Parse (dataLine[0].Trim()); if (curID == clientID) { //this dataline is for this client int compartmentNum = int.Parse(dataLine[1]); int hour = int.Parse(dataLine[2]); int minute = int.Parse(dataLine[3]); string pills = dataLine[4].Trim(); myCompartments[compartmentNum-1].hour = hour; myCompartments[compartmentNum-1].minute = minute; myCompartments[compartmentNum-1].pills = pills; } } }
/// <summary> /// Carrega as informações do arquivo de configuração do E-mail. /// </summary> /// <returns></returns> public static Email CarregarInformacoesLoginServidor() { Cryptor cr; string CaminhoDoArquivo = String.Format("{0}/Email.dat", Ferramentas.ObterCaminhoDoExecutavel()); Email EmailBase = new Email(); StreamReader sr = null; cr = new Cryptor("[email protected]$$w0rd"); try { sr = new StreamReader(CaminhoDoArquivo); EmailBase.email = cr.Decrypt(sr.ReadLine()); EmailBase.Senha = cr.Decrypt(sr.ReadLine()); EmailBase.Host = cr.Decrypt(sr.ReadLine()); EmailBase.Port = int.Parse(cr.Decrypt(sr.ReadLine())); } catch (System.Exception exc) { ControllerArquivoLog.GeraraLog(exc); } finally { if (sr != null) sr.Close(); } return EmailBase; }
private static void ExecuteCommands() { var reader = new StreamReader("..//..//Commands.txt"); string line = reader.ReadLine(); using (reader) { while (line != null) { string[] data = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); var commandName = data[0]; if (commandName.ToLower() == "find") { Console.WriteLine( "The command 'find' with parameters {0} returned the following results:", data.Length == 3 ? string.Join(",", new[] { data[1], data[2] }) : data[1]); if (data.Length == 3) { var result = book.Find(data[1], data[2]); Console.WriteLine(string.Join("\n", result)); } else { Console.WriteLine(string.Join("\n", book.Find(data[1]))); } } line = reader.ReadLine(); } } }
public void Run() { using (var reader = new StreamReader("jobs.txt")) using (var writer = new StreamWriter("output.txt")) { var jobs = new List<Job>(); reader.ReadLine(); while (true) { string row = reader.ReadLine(); if (row == null) { break; } var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); var numbers = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture)).ToArray(); jobs.Add(new Job(numbers[0], numbers[1])); } var weightedSum1 = JobScheduler.GetWeightedSumOfCompletionTimes(jobs, JobScheduler.CompareByDifference); writer.WriteLine(weightedSum1); var weightedSum2 = JobScheduler.GetWeightedSumOfCompletionTimes(jobs, JobScheduler.CompareByRatio); writer.WriteLine(weightedSum2); } }
public static List<Path> LoadPath() { Path pathToLoad = new Path(); List<Path> pathsList = new List<Path>(); using (StreamReader reader = new StreamReader(@"..\..\LoadPaths.txt")) { string newLine = reader.ReadLine(); while (newLine != string.Empty) { Point3D newPoint = new Point3D(); newLine = reader.ReadLine(); newPoint.X = int.Parse(newLine); newLine = reader.ReadLine(); newPoint.Y = int.Parse(newLine); newLine = reader.ReadLine(); newPoint.Z = int.Parse(newLine); pathToLoad.AddPoint(newPoint); newLine = reader.ReadLine(); pathsList.Add(pathToLoad); pathToLoad = new Path(); } } return pathsList; }
// Load an array of training set items from the csv file public static List<TrainingItem> Load(string csvFile) { List<TrainingItem> trainingItems = new List<TrainingItem>(); string line; string[] items; // Read the file and display it line by line. System.IO.StreamReader file = new System.IO.StreamReader(csvFile); // Skip the first line since it is the header file.ReadLine(); while ((line = file.ReadLine()) != null) { TrainingItem trainingItem = new TrainingItem(); items = line.Split(','); trainingItem.FileName = items[0]; trainingItem.Label = items[1]; trainingItems.Add(trainingItem); } file.Close(); return trainingItems; }
private static void Main() { var fileOne = new StreamReader(@"..\..\fileOne.txt"); var fileTwo = new StreamReader(@"..\..\fileTwo.txt"); using (fileOne) { using (fileTwo) { var fileOneLine = fileOne.ReadLine(); var fileTwoLine = fileTwo.ReadLine(); var currentLine = 0; var matchingLines = 0; while (fileOneLine != null || fileTwoLine != null) { currentLine++; if (fileTwoLine == fileOneLine) { matchingLines++; } fileOneLine = fileOne.ReadLine(); fileTwoLine = fileTwo.ReadLine(); } Console.WriteLine( "There are {0} line(s) that are the same and {1} that are different", matchingLines, currentLine - matchingLines); } } }
public CMusicHit(String path) { int counter = 0; this._next = 0; string line; StreamReader hitFile = new StreamReader(path); line = hitFile.ReadLine(); this._length = int.Parse(line); line = hitFile.ReadLine(); this._speed = int.Parse(line); line = hitFile.ReadLine(); this._endTime = int.Parse(line); this._time = new int[this._length]; this._position = new int[this._length]; while ((line = hitFile.ReadLine()) != null) { if (line.Contains('t')) { line = line.Substring(line.IndexOf(':')+1); this._time[counter] = int.Parse(line); } else { line = line.Substring(line.IndexOf(':')+1); this._position[counter] = int.Parse(line); counter++; } } }
static void Main(string[] args) { using (StreamReader orig = new StreamReader("orig.txt")) { int lineNumber = 0; string line = orig.ReadLine(); while (line != null) { lineNumber++; if (lineNumber % 2 == 0) { StreamWriter even = new StreamWriter("even.txt", true); { even.WriteLine(line); } even.Close(); } else { StreamWriter odd = new StreamWriter("odd.txt", true); { odd.WriteLine(line); } odd.Close(); } line = orig.ReadLine(); } } Console.WriteLine("Your text is separated by even and odd lines in two separated files."); Console.WriteLine("Check your folder to see the result!"); Console.WriteLine(); }
/// <summary> /// Fetches the list of servers and adds them to serverView's server collection /// </summary> public void fetchServers() { WebRequest serverReq = WebRequest.Create("http://kaillera.com/raw_server_list2.php?version=0.9"); WebResponse serverResp = serverReq.GetResponse(); using (StreamReader sr = new StreamReader(serverResp.GetResponseStream())) { while (!sr.EndOfStream) { try { Server currServer = new Server(); currServer.name = sr.ReadLine(); string[] servInfo = sr.ReadLine().Split(';'); string[] ipPort = servInfo[0].Split(':'); currServer.ip = IPAddress.Parse(ipPort[0]); currServer.port = int.Parse(ipPort[1]); currServer.users = int.Parse(servInfo[1].Split('/')[0]); currServer.numGames = int.Parse(servInfo[2]); currServer.version = servInfo[3]; currServer.location = servInfo[4]; addServers(currServer); } catch (Exception) { log.Warn("Invalid server detected!"); } } } }
public Read(Stream myStream) { string aux; string[] pieces; //read the file line by line StreamReader sr = new StreamReader(myStream); aux = sr.ReadLine(); header = aux.Split(','); nColumns = header.Length; nLines = 0; while ((aux = sr.ReadLine()) != null) { if (aux.Length > 0) nLines++; } //read the numerical data from file in an array data = new float[nLines, nColumns]; sr.BaseStream.Seek(0, 0); sr.ReadLine(); for (int i = 0; i < nLines; i++) { aux = sr.ReadLine(); pieces = aux.Split(','); for (int j = 0; j < nColumns; j++) data[i, j] = float.Parse(pieces[j]); } sr.Close(); }
static void Main(string[] args) { string fileName1 = @"..\..\file1.txt"; string fileName2 = @"..\..\file2.txt"; StreamReader reader1 = new StreamReader(fileName1); StreamReader reader2 = new StreamReader(fileName2); int countEqual = 0; int countDifferent = 0; string line1 = reader1.ReadLine(); string line2 = reader2.ReadLine(); while (line1 != null) { if (line1 == line2) { countEqual++; } else { countDifferent++; } line1 = reader1.ReadLine(); line2 = reader2.ReadLine(); } reader1.Close(); reader2.Close(); Console.WriteLine("Equal lines number -> {0}", countEqual); Console.WriteLine("Different lines number -> {0}", countDifferent); }
static void Main() { StreamWriter writerFirst = new StreamWriter(@"..\..\test.txt",false); using (writerFirst) { StreamReader readFirstDoc = new StreamReader(@"..\..\Concat.cs"); //The first document is the Concat.cs. using (readFirstDoc) { string lineDoc1 = readFirstDoc.ReadLine(); while(lineDoc1!=null) { writerFirst.WriteLine(lineDoc1); lineDoc1=readFirstDoc.ReadLine(); } } } StreamWriter writerSecond = new StreamWriter(@"..\..\test.txt", true); using(writerSecond) { StreamReader readSecondDoc = new StreamReader(@"..\..\App.config"); //The second document is App.config using (readSecondDoc) { string lineDoc2 = readSecondDoc.ReadLine(); while (lineDoc2 != null) { writerSecond.WriteLine(lineDoc2); lineDoc2 = readSecondDoc.ReadLine(); } } } Console.WriteLine("Concatenation finished!"); }
private void ReadFromStream(StreamReader stream) { int id = 0; string nextLine; while ((nextLine = stream.ReadLine()) != null) { string[] records = nextLine.Trim().Split(';'); if (records.Length == 4) { string source = records[0].Trim(); string message = records[1].Trim(); string messageLevel = records[2].Trim(); DateTime timestamp = DateTime.Parse(records[3].Trim()); items.Add(new LogItem(id, source, message, messageLevel, timestamp)); id++; nextLine = stream.ReadLine(); } else { nextLine += stream.ReadLine(); } } }
public static string[] GetColumnNames(string filename, int nskip, HashSet<string> commentPrefix, HashSet<string> commentPrefixExceptions, Dictionary<string, string[]> annotationRows, char separator) { StreamReader reader = new StreamReader(filename); for (int i = 0; i < nskip; i++){ reader.ReadLine(); } string line = reader.ReadLine(); if (commentPrefix != null){ while (IsCommentLine(line, commentPrefix, commentPrefixExceptions)){ line = reader.ReadLine(); } } string[] titles = line.Split(separator); if (annotationRows != null){ while ((line = reader.ReadLine()) != null){ if (!line.StartsWith("#!{")){ break; } int end = line.IndexOf('}'); if (end == -1){ continue; } string name = line.Substring(3, end - 3); string w = line.Substring(end + 1); string[] terms = w.Split(separator); annotationRows.Add(name, terms); } } reader.Close(); return titles; }
static void Main() { var reader = new StreamReader("..\\..\\Matrix.txt"); int n = int.Parse(reader.ReadLine()); int[,] matrix = new int[n, n]; for (int row = 0; row < n; row++) { string[] textLine = reader.ReadLine().Split(' '); for (int col = 0; col < n; col++) { matrix[row, col] = int.Parse(textLine[col]); } } reader.Close(); int bestSum = int.MinValue; int bestRow = 0; int bestCol = 0; for (int row = 0; row < matrix.GetLength(0) - 1; row++) { for (int col = 0; col < matrix.GetLength(1) - 1; col++) { int sum = matrix[row, col] + matrix[row, col + 1] + matrix[row + 1, col] + matrix[row + 1, col + 1]; if (sum > bestSum) { bestSum = sum; bestRow = row; bestCol = col; } } } Console.WriteLine(bestSum); }
static void Main(string[] args) { //Write a program that reads a text file and prints on the console its odd lines. string path = @"C:\Users\Ivan\Desktop\test.txt"; Encoding utf8 = Encoding.GetEncoding("UTF-8"); Encoding win1251 = Encoding.GetEncoding("Windows-1251"); try { StreamReader fileReader = new StreamReader(path, win1251); using (fileReader) { int lineNum = 0; string line = fileReader.ReadLine(); while (line != null) { lineNum++; if (lineNum % 2 != 0) { Console.WriteLine("Line {0}: {1}", lineNum, line); } line = fileReader.ReadLine(); } } } catch (Exception) { Console.WriteLine("Error!"); } }
static void Main(string[] args) { StreamReader read = StreamReader.Null; StreamWriter write = StreamWriter.Null; string line; int lineNumber = 0; try { read = new StreamReader("../../text.txt"); write = new StreamWriter("../../numbered_text.txt"); } catch (Exception e) { Console.WriteLine("The file could not be read/created:"); Console.WriteLine(e.Message); } using (read) using (write) { line = read.ReadLine(); while (line != null) { write.WriteLine("{0,4} {1}", lineNumber, line); lineNumber++; line = read.ReadLine(); } } Console.WriteLine("Success!"); }
private void bnConnect_Click(object sender, EventArgs e) { try { client = new TcpClient(txtConnect.Text, 2000); ns = client.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); dato = sr.ReadLine() + System.Environment.NewLine + sr.ReadLine() + System.Environment.NewLine + sr.ReadLine(); DelegadoRespuesta dr = new DelegadoRespuesta(EscribirFormulario); Invoke(dr); } catch (Exception err) { Console.WriteLine(err.ToString()); throw; } }
List<Show> Grab(GrabParametersBase p) { var pp = (GrabParameters)p; var url = string.Format(URL, pp.FromDate.ToString("dd/MM/yyyy"), pp.ToDate.ToString("dd/MM/yyyy")); var wr = WebRequest.Create(url); _logger.WriteEntry("Grabbing BBCW", LogType.Info); var res = (HttpWebResponse)wr.GetResponse(); using (var sr = new StreamReader(res.GetResponseStream())) { var lst = new List<Show>(); sr.ReadLine(); // first line while (!sr.EndOfStream) { var line = sr.ReadLine(); if (!string.IsNullOrEmpty(line) && line.Length > 10) { var show = new Show(); show.Channel = "BBC World News"; var tokens = line.Split('\t'); show.StartTime = DateTime.SpecifyKind(Convert.ToDateTime(tokens[0]) + Convert.ToDateTime(tokens[1]).TimeOfDay, DateTimeKind.Unspecified); show.StartTime = TimeZoneInfo.ConvertTime(show.StartTime, TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"), TimeZoneInfo.Utc); show.Title = tokens[2]; //show.Episode = string.IsNullOrEmpty(tokens[3]) ? null : (int?)Convert.ToInt32(tokens[3]); // not number show.Description = tokens[4]; lst.Add(show); } } return lst; } }
private void button1_Click(object sender, EventArgs e) { //获得串口参数配置文件的路径 string CfgFilePath = Application.StartupPath + "\\ConfigFile\\SerialPortCfg"; //创建写文件流 StreamWriter sw = new StreamWriter(CfgFilePath, false); //将串口参数写入文件 sw.Write(comboBox1.SelectedItem + "\r\n"); sw.Write(comboBox2.SelectedItem + "\r\n"); sw.Write(comboBox3.SelectedItem + "\r\n"); sw.Write(comboBox4.SelectedItem + "\r\n"); sw.Write(comboBox5.SelectedItem + "\r\n"); //关闭流 sw.Close(); //创建读文件流 StreamReader sr = new StreamReader(CfgFilePath); //显示串口参数 label6.Text = sr.ReadLine(); label7.Text = sr.ReadLine(); label8.Text = sr.ReadLine(); label9.Text = sr.ReadLine(); label10.Text = sr.ReadLine(); //关闭流 sr.Close(); MessageBox.Show(this, "设置成功。 ", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); //关串口参数设置窗体 }
public void Read(Stream s) { var r = new StreamReader(s); this.Reader = r; var h = r.ReadLine(); if (string.IsNullOrEmpty(h)) return; var Method_i = h.IndexOf(" "); var Method_key = h.Substring(0, Method_i); var Method_value = h.Substring(Method_i + 1, h.IndexOf(" ", Method_i + 1) - (Method_i + 1)); if (Method != null) Method(Method_key, Method_value); while (!string.IsNullOrEmpty(h)) { h = r.ReadLine(); if (!string.IsNullOrEmpty(h)) { var Header_key = h.Substring(0, h.IndexOf(":")); var Header_value = h.Substring(h.IndexOf(":") + 1).Trim(); if (Header != null) Header(Header_key, Header_value); } } }
internal static List<List<string>> ParseCsvFile(string path) { var allIssues = new List<List<string>>(); using (var readFile = new StreamReader(path)) { var header = ParseCsvLine(readFile.ReadLine()); string line; while ((line = readFile.ReadLine()) != null) { var newIssue = ParseCsvLine(line); if (string.IsNullOrEmpty(newIssue[0])) { for(int i = 0; i < newIssue.Count; i++) { if (!string.IsNullOrEmpty(newIssue[i])) { allIssues[allIssues.Count - 1][i] += (Environment.NewLine + newIssue[i]); } } } else { ValidateCsvLine(newIssue); allIssues.Add(newIssue); } } } return allIssues; }
public static void Main(string[] args) { StreamReader reader = new StreamReader(@"..\..\students.txt"); using (reader) { SortedDictionary<string, OrderedBag<Student>> students = new SortedDictionary<string, OrderedBag<Student>>(); for (string line = reader.ReadLine(); line != null; line = reader.ReadLine()) { var input = line.Split('|'); if (!students.ContainsKey(input[2].Trim())) { var grouped = new OrderedBag<Student>(); grouped.Add(new Student(input[0].Trim(), input[1].Trim())); students.Add(input[2].Trim(), grouped); } else { students[input[2].Trim()].Add(new Student(input[0].Trim(), input[1].Trim())); } } foreach (var student in students) { Console.WriteLine(student); } } }
private IEnumerable<Record> ReadRecords(string fileName) { var stringBuilder = new StringBuilder(); using (var reader = new StreamReader(fileName)) { ReadOnlyCollection<string> header; if (reader.Peek() >= 0) { var first = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray(); header = new ReadOnlyCollection<string>(first); } else { yield break; } for (var i = 0; i < this._numberRecordsToSkip && reader.Peek() >= 0; i++) { reader.ReadLine(); } while (reader.Peek() >= 0) { var items = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray(); yield return new Record(header, items); } } }
static void Main(string[] args) { string line; try { FileStream aFile = new FileStream("Log.txt", FileMode.Open); StreamReader sr = new StreamReader(aFile); line = sr.ReadLine(); // Read data in line by line. while (line != null) { Console.WriteLine(line); line = sr.ReadLine(); } sr.Close(); } catch (IOException e) { Console.WriteLine("An IO exception has been thrown!"); Console.WriteLine(e.ToString()); return; } Console.ReadKey(); }
private SimpleFileHistoryManager() { _totalHistoryFilePath = Properties.Settings.Default.UtteranceLibrariesDirectory + @"\history.txt"; if (!File.Exists(_totalHistoryFilePath)) File.Create(_totalHistoryFilePath).Dispose(); using (TextReader reader = new StreamReader(_totalHistoryFilePath)) { string line = reader.ReadLine(); try { while (line != null) { string[] splitted = line.Split(','); _totalHistory.Add(new Utterance( splitted[0], splitted[1], splitted[2], splitted[3], splitted[4], splitted[5], splitted[6] )); line = reader.ReadLine(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } _instance = this; }
//Write a program that reads a text file containing a square matrix of numbers. //Find an area of size 2 x 2 in the matrix, with a maximal sum of its elements. //The first line in the input file contains the size of matrix N. //Each of the next N lines contain N numbers separated by space. //The output should be a single number in a separate text file. static void Main(string[] args) { StreamReader reader = new StreamReader(@"..\..\file.txt"); using (reader) { string line = reader.ReadLine(); int number = int.Parse(line); int[,] array = new int[number, number]; for (int i = 0; i < number; i++) { string[] numbers = reader.ReadLine().Split(' '); for (int k = 0; k < number; k++) { array[i, k] = int.Parse(numbers[k]); } } int bestsum = int.MinValue; for (int row = 0; row < array.GetLength(0) - 1; row++) { for (int col = 0; col < array.GetLength(1) - 1; col++) { int sum = array[row, col] + array[row, col + 1] + array[row + 1, col] + array[row + 1, col + 1]; if (sum > bestsum) { bestsum = sum; } } } Console.WriteLine(bestsum); } }