Search code examples
c#text-filessubtraction

Is there a way to subtract from a number that is in a txt file c#


Hi I am New to C# and could do with some help. I have a programme that currently save`s Events to there own text file which contains the details about the event(the details are entered by the user). One of these details is The Amount Of tickets. I am having trouble with making it so that when a ticket is brought the amount decreases by one.

I would like to Know If there Is Anyway For me to subtract 1 from a Number that is on a Text File. this is how my Text Files Are laid out:

Event Name: Test
Event Time: 12:30
Event Location: Test
Amount Of Tickets: 120
Price Of Tickets: £5

This is the method i tried and all this did was add -1 -1 to the value instead of taking away from the value:

Console.WriteLine("What Event Would You Like To Buy A Ticket For?");
            string EventUpdate = Console.ReadLine(); 
            string folderPath = (@"A:\Work\Visual Studio\TextFiles");
            string fileName = EventUpdate + ".txt";
            string filePath = folderPath + "\\" + fileName;  //creats file path using FolderPath Plus users Input
            string Contents = File.ReadAllText(filePath);
            Console.WriteLine(Contents); //displays the txt file that was called for
            Console.WriteLine("\n");
            string FindText = "Amount Of Tickets:";
            int I = -1;
            string NewText = FindText + I;
            string NewTempFile = folderPath + EventUpdate + ".txt";
            string file = filePath;
            File.WriteAllText(file, File.ReadAllText(file).Replace(FindText, NewText));


            using (var sourceFile = File.OpenText(file))
            {
                // Create a temporary file path where we can write modify lines
                string tempFile = Path.Combine(Path.GetDirectoryName(file), NewTempFile);
                // Open a stream for the temporary file
                using (var tempFileStream = new StreamWriter(tempFile))
                {
                    string line;
                    // read lines while the file has them
                    while ((line = sourceFile.ReadLine()) != null)
                    {

                        // Do the Line replacement
                        line = line.Replace(FindText, NewText);
                        // Write the modified line to the new file
                        tempFileStream.WriteLine(line);
                    }
                }
            }
            // Replace the original file with the temporary one
            File.Replace(NewTempFile, file, null);

this is what happened to my text file when i used the above code:

 Event Name: Test
 Event Time: 12:30
 Event Location: Test
 Amount Of Tickets:-1-1 120
 Price Of Tickets: £5 

Solution

  • There are oodles of way to do this... However, you need to convert a your "text number" to an actual number (in this case an integer) to perform mathematical operations on it

    // get the lines in an array
    var lines = File.ReadAllLines(file);
    
    // iterate through every line
    for (var index = 0; index < lines.Length; index++)
    {
       // does the line start with the text you expect?
       if (lines[index].StartsWith(findText))
       {
          // awesome, lets split it apart
          var parts = lines[index].Split(':');
          // part 2 (index 1) has your number
          var num = int.Parse(parts[1].Trim());
          // recreate the line minus 1
          lines[index] = $"{findText} {num-1}";
          // no more processing needed
          break;
       }    
    }
    // write the lines to the file
    File.WriteAllLines(file, lines);
    

    Note : even if this doesn't work (and i haven't checked it) you should have enough information to continue unaided


    Additional Resources

    String.StartsWith Method

    Determines whether the beginning of this string instance matches a specified string.

    String.Split Method

    Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

    String.Trim Method

    Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.

    Int32.Parse Method

    Converts the string representation of a number to its 32-bit signed integer equivalent.

    File.ReadAllLines Method

    Opens a text file, reads all lines of the file into a string array, and then closes the file.

    File.WriteAllLines Method

    Creates a new file, writes one or more strings to the file, and then closes the file.

    $ - string interpolation (C# Reference)

    The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.