您好,我是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
答案 0 :(得分:1)
有很多方法可以执行此操作...但是,您需要将“文本编号”转换为实际编号(在这种情况下为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);
注意 :即使这行不通(并且我没有检查过),您也应该有足够的信息来继续进行援助
其他资源
确定此字符串实例的开头是否与 指定的字符串。
返回一个字符串数组,该数组包含此实例中的子字符串 由指定的字符串或Unicode元素分隔的 字符数组。
返回一个新字符串,其中所有前导和尾随出现 当前String对象中的一组指定字符是 删除。
将数字的字符串表示形式转换为其32位带符号 等价的整数。
打开一个文本文件,将文件的所有行读入字符串数组, 然后关闭文件。
创建一个新文件,向该文件写入一个或多个字符串,然后 关闭文件。
$ - string interpolation (C# Reference)
$特殊字符将字符串文字标识为插值 串。插值字符串是可能包含以下内容的字符串文字 插值表达式。当插值字符串解析为 结果字符串,带有插值表达式的项目将替换为 表达式结果的字符串表示形式。此功能是 在该语言的C#6和更高版本中可用。
答案 1 :(得分:0)
我附上了修改后的代码,并添加了有效的注释
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);
}
}
}