C# 有没有办法从txt文件c中的数字中减去#

C# 有没有办法从txt文件c中的数字中减去#,c#,text-files,subtraction,C#,Text Files,Subtraction,嗨,我是C#的新手,需要一些帮助。我有一个程序,目前将的事件保存到自己的文本文件中,该文件包含有关事件的详细信息(详细信息由用户输入)。其中一个细节是门票数量。我很难做到这样,当一张票带来时,数量会减少一 我想知道我是否有办法从文本文件中的数字中减去1。 以下是我的文本文件的布局方式: Event Name: Test Event Time: 12:30 Event Location: Test Amount Of Tickets: 120 Price Of Tickets: £5 这是我尝试

嗨,我是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 

有很多方法可以做到这一点。。。但是,您需要将“文本号”中的数字转换为实际数字(在本例中为
整数
)才能对其执行数学运算

// 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);
//获取数组中的行
var lines=File.ReadAllLines(文件);
//遍历每一行
对于(变量索引=0;索引<行.长度;索引++)
{
//行是否以您期望的文本开头?
if(行[index].StartsWith(findText))
{
//太棒了,让我们分开吧
var parts=lines[index].Split(“:”);
//第2部分(索引1)有您的编号
var num=int.Parse(parts[1].Trim());
//重新创建减去1的行
行[索引]=$“{findText}{num-1}”;
//不需要更多的处理
打破
}    
}
//将这些行写入文件
File.writeAllines(文件,行);
注意:即使这不起作用(我没有检查),您也应该有足够的信息在没有帮助的情况下继续


其他资源

确定此字符串实例的开头是否与 指定的字符串

返回包含此实例中的子字符串的字符串数组 由指定字符串或Unicode的元素分隔的 字符数组

返回一个新字符串,其中 当前字符串对象中的一组指定字符是 删除

将数字的字符串表示形式转换为其32位有符号 整数等价

打开一个文本文件,将文件的所有行读入字符串数组, 然后关闭文件

创建新文件,将一个或多个字符串写入该文件,然后 关闭文件

$special字符将字符串文字标识为插值字符 一串插值字符串是可能包含以下内容的字符串文字 插值表达式。当插值字符串解析为 结果字符串中,带有插值表达式的项将替换为 表达式结果的字符串表示形式。此功能是 可在C#6和更高版本的语言中获得


我附加了一个修改版本的代码,添加了coments,可以正常工作

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

如果你能准确地解释你想做什么,这会很有帮助。我猜你想从
票数:120减去
1
,然后将其写入一个新文件?所以上面写着:
门票数量:119
?是的,这正是我想做的。谢谢你,将军,这个代码正是我想要的。