有没有办法从 txt 文件 c# 中的数字中减去
Is there a way to subtract from a number that is in a txt file c#
您好,我是 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
有很多方法可以做到这一点...但是,您需要将 "text number" 转换为实际数字(在本例中为 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);
注意:即使这不起作用(而且我还没有检查过)你应该有足够的信息继续独立
其他资源
Determines whether the beginning of this string instance matches a
specified string.
Returns a string array that contains the substrings in this instance
that are delimited by elements of a specified string or Unicode
character array.
Returns a new string in which all leading and trailing occurrences of
a set of specified characters from the current String object are
removed.
Converts the string representation of a number to its 32-bit signed
integer equivalent.
Opens a text file, reads all lines of the file into a string array,
and then closes the file.
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.
我附上了您代码的修改版本,添加了有效的注释
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);
}
}
}
您好,我是 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
有很多方法可以做到这一点...但是,您需要将 "text number" 转换为实际数字(在本例中为 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);
注意:即使这不起作用(而且我还没有检查过)你应该有足够的信息继续独立
其他资源
Determines whether the beginning of this string instance matches a specified string.
Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.
Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.
Converts the string representation of a number to its 32-bit signed integer equivalent.
Opens a text file, reads all lines of the file into a string array, and then closes the file.
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.
我附上了您代码的修改版本,添加了有效的注释
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);
}
}
}