我正在尝试为我的Discord Server的机器人创建一个"警告系统",在此使用该命令时,它将从文本文件中获取信息,然后将其更新。我可以在某种程度上设想我想逐步发生的事情,但是我对如何从文件中读取内容的内容感到困惑:
鲍勃#5368 3
标记#8459 6
辛迪#1254 2
我只想更改名称背后的数字,我不确定如何基本上找到要寻找的用户,然后将数字设置为" TotalWarn",然后加上(TotalWarn = Warnnum),然后使用新数字更新该用户。
注意:'警告文件'是该代码块之外已经定义的文件路径。
public async Task warn(IGuildUser user, int warnNum, [Remainder] string reason)
{
int totalWarn = 0;
if (user == null)
await ReplyAsync("Please include a name");
if (warnNum <= 0)
await ReplyAsync("The warning level must increase by 1 or more.");
if (reason == null)
await ReplyAsync("Please include a reason.");
string nickName = user.Username;
//Check for whether text file exists or not.
if (!File.Exists(warningFile))
{
//Create the File
FileStream fs = File.Create(warningFile);
}
//Reads all the text in the file and puts it into an array.
string[] arr = File.ReadAllLines(warningFile);
for (int i = 0; i < arr.Length; i++)
{
string line = arr[i];
}
totalWarn = +warnNum;
await Context.Channel.SendMessageAsync($"{user.Username}'s warning level has increased by {warnNum} for {reason}.n"
+ $"Your warning level is now {totalWarn}. Please take this time to review the server rules.");
}
我不是在寻找有人为我完成它,只是一些帮助,因为我完全迷失了自己的方向,并且有关更改文本的信息也不会有帮助。
<</p>这是如何使用REGEX从文件中解析一行的方法:
void Main()
{
string line = "bob#5368 3";
GuildUser user = new GuildUser( line );
user.Warnings++;
user.ToString().Dump();
}
public class GuildUser
{
public string Name { get; set;}
public int Id { get; set;}
public int Warnings { get; set;}
public GuildUser( string line )
{
Match match = Regex.Match( line, @"(.+)?#(d+) (d+)" );
if ( !match.Success ) throw new Exception( "Couldn't parse line: " + line );
Name = match.Groups[1].Value;
Id = int.Parse( match.Groups[2].Value );
Warnings = int.Parse( match.Groups[3].Value );
}
public override string ToString()
{
return $"{Name}#{Id} {Warnings}";
}
}
您可以使用file.ReadAlllines,file.writealllines。
我可能还会使用一些Linq。
我更新以添加" tostring"方法来重写该行。然后,您只需添加警告并获取新的字符串调用ToString()。
另一种方式:
public static void stuff()
{
string name = "bob";
string firstNumber = "";
string secondNumber = "";
int lineIndex = 0;
List<string> lines = new List<string>(File.ReadAllLines(@"C:Text.txt"));
foreach(string line in lines)
{
if(line.Contains(name))
{
lineIndex = lines.IndexOf(line);
string[] parts = line.Split('#');
name = parts[0];
firstNumber = parts[1].Split(' ')[0];
secondNumber = parts[1].Split(' ')[1];
firstNumber = (Convert.ToInt32(firstNumber) + 1).ToString();
/*
* instert code here for changing the number you want to change
*/
lines[lineIndex] = name + "#" + firstNumber + " " + secondNumber;
File.WriteAllLines(@"C:Text.txt",lines.ToArray());
break;
}
}
}