How do I edit/replace a specific value in a .txt file using StreamWriter?

246 views Asked by At

I have code in which I am reading in my .txt file. The text file contains values of first and last name, and a number.

"Daniel" "Murrow" "1234"

I am trying to use StreamWriter to edit a specific value. However, my code as of now edits the whole .txt file and replaces everything. I would only like to replace the number value in my case.

static classMates[] readClassMates(classMates[] classMateInfo)
    {
        StreamReader sr = new StreamReader(@"C:\Users\Callum\Documents\class.txt");
        int count = 0;
        while (!sr.EndOfStream)
        {
            classMateInfo[count].first = sr.ReadLine();
            classMateInfo[count].last = sr.ReadLine();
            string idTemp = sr.ReadLine();
            classMateInfo[count].ID = Convert.ToInt32(idTemp);
            count++;
        }
        sr.Close();
        return classMateInfo;

static void editClassMates(classMates[] classMateInfo)
    {
        Console.Write("Who's number would you like to change? ");
        string classMateInput = Console.ReadLine();
        for (int i = 0; i < classMateInfo.Length; i++)
        {
            if (classMateInfo[i].last.Equals(classMateInput))
            {

                Console.Write("Enter new number: ");
                string temp = Console.ReadLine();
                int classMateNumber = Convert.ToInt32(temp);
                StreamWriter sw = new StreamWriter(@"C:\Users\Callum\Documents\class.txt");
                for (int j = 0; j < classMateInfo.Length; j++)
                {
                    sw.WriteLine(classMateNumber);
                }
                sw.Close();

            }
        }

    }

So my question is, how do I edit a specific value in my .txt file? I've tried my best, but I've been stuck on this for ages!

1

There are 1 answers

1
James Lucas On

If the file is not very big (and therefore memory usage is not an issue) how about this:

var text = File.ReadAllText(@"C:\Users\Callum\Documents\class.txt");
var updatedText = text.Replace(...); // Do your string replacement here
File.WriteAllText(@"C:\Users\Callum\Documents\class.txt");