Есть ли способ вычесть из числа, которое находится в текстовом файле c # - PullRequest
0 голосов
/ 04 января 2019

Привет, я новичок в C # и могу сделать с некоторой помощью.У меня есть программа, которая в настоящее время сохраняет события в своем собственном текстовом файле, который содержит подробную информацию о событии (детали вводятся пользователем).Одной из таких деталей является количество билетов.У меня возникают проблемы с тем, чтобы при получении билета сумма уменьшалась на единицу.

Я хотел бы знать, есть ли для меня возможность вычесть 1 из числа в текстовом файле.Вот как устроены мои текстовые файлы:

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

Это метод, который я попробовал, и все, что он сделал, это добавил -1 -1 к значению вместо того, чтобы убирать значение:

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);

это то, что случилось с моим текстовым файлом, когда я использовал приведенный выше код:

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

Ответы [ 2 ]

0 голосов
/ 04 января 2019

Я прилагаю модифицированную версию вашего кода с добавленными комментариями, которая работает

using System;
using System.IO;
namespace New_Folder
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What Event Would You Like To Buy A Ticket For?");
            string EventUpdate = Console.ReadLine();
            string folderPath = ("TextFiles");
            string fileName = EventUpdate + ".txt";
            string filePath = fileName; //creats file path using FolderPath Plus users Input
            string[] Contents = File.ReadAllLines(filePath); //Puts each line content into array element

            foreach (var line in Contents)
            {
                System.Console.WriteLine(line); //displays the txt file that was called for
            }

            Console.WriteLine("\n");

            int LineWithAmountOfTicketIndex = 3;
            string LineWithAmountOfTicketText = Contents[LineWithAmountOfTicketIndex];

            string[] AmountLineContent = LineWithAmountOfTicketText.Split(':'); // Splits text by ':' sign and puts elements into an array, e.g. "one:two" would be split into "one" and "two"
            int TicketNumber = Int32.Parse(AmountLineContent[1]); // Parses the ticket number part from a string to int (check out TryParse() as well)
            int SubtractedTicketNumber = --TicketNumber; //subtract one from ticket number before assigning to a variable

            string NewText = $"{AmountLineContent[0]}: {SubtractedTicketNumber}";
            string NewTempFile = folderPath + EventUpdate + ".txt";
            string file = filePath;
            File.WriteAllText(file, File.ReadAllText(file).Replace(LineWithAmountOfTicketText, 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(LineWithAmountOfTicketText, 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);
        }
    }
}
0 голосов
/ 04 января 2019

Существует множество способов сделать это ... Однако вам необходимо преобразовать ваше «текстовое число» в фактическое число (в данном случае integer), чтобы выполнить математические операции над ним

// 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);

Примечание : даже если это не сработает (и я не проверил это), у вас должно быть достаточно информации, чтобы продолжить без посторонней помощи


Дополнительные ресурсы

String.StartsWith Method

Определяет, соответствует ли начало этого экземпляра строки указанной строке.

Метод String.Split

Возвращает строковый массив, содержащий в этом экземпляре подстроки, разделенные элементами указанной строки или массива символов Unicode.

Метод String.Trim

Возвращает новую строку, в которой все начальные и конечные вхождения набора указанных символов из текущего объекта Stringудалены.

Int32.Parse Method

Преобразует строковое представление числа в его 32-разрядный эквивалент целого числа со знаком.

Метод File.ReadAllLines

Открывает текстовый файл, считывает все строки файла в массив строк, а затем закрывает файл.

File.WriteAllLines Метод

Создает новый файл, записывает одну или несколько строк в файл, а затем закрывает файл.

$ - интерполяция строк (C #Ссылка)

Специальный символ $ идентифицирует строковый литерал как интерполированную строку.Интерполированная строка - это строковый литерал, который может содержать интерполированные выражения.Когда интерполированная строка преобразуется в результирующую строку, элементы с интерполированными выражениями заменяются строковыми представлениями результатов выражения.Эта функция доступна в C # 6 и более поздних версиях языка.

...