Search code examples
c#filestream

C# compare id from text file in filestream


I need to fill a text file with information about workers. Then I need to read from the file and search for an ID that user tries to find. For example my file contains ids 1,2,3 and if I try to find id 3 and it matches, then this worker's all information is written in console. Otherwise it writes a text A worker cannot be found.

using System;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        string file = "C:\\Temp\\registery.txt";
        FileStream fOutStream = File.Open(file, FileMode.Append, FileAccess.Write);
        StreamWriter sWriter = new StreamWriter(fOutStream);
        int[] id = {     1, 2, 3     };
        string[] name = {     "John", "Carl", "Thomas"     };
        float[] salary = {     3500, 4800, 2100     };
        for (int i = 0; i < id.Length; i++)
        {
            sWriter.WriteLine(id[i] + " " + name[i] + " " + salary[i]);
        }
        sWriter.Flush();
        sWriter.Close();
        FileStream fInStream = File.OpenRead(file);
        StreamReader sReader = new StreamReader(fInStream);
        int id2;
        Console.WriteLine("Type worker's id");
        id2 = int.Parse(Console.ReadLine());
        bool a;
        a = sReader.ReadToEnd().Contains(id2);
        Console.WriteLine(a);
        sReader.Close();
    }
}

Solution

  • I found a solution myself to my problem and it worked good enough. It might not be the best solution. I removed bool things and I replaced the whole thing with this:

    string line;
        while ((line = sReader.ReadLine()) != null)
        {
            if (line.Contains("id: " + id2))
            {
                Console.WriteLine(line);
                break;
            }
            else if ((line = sReader.ReadLine()) == null)
            {
                Console.WriteLine("Worker not found with id " + id2);
    
            }
         }
    

    And I fixed the upper for loop to look like this:

    sWriter.WriteLine("id: " + id[i] + " name: " + name[i] + " salary: " + salary[i]);