解析时字符串未被识别为有效的 DateTime

String was not recognised as a valid DateTime when parsing

所以我有一些代码可以将当前日期时间写入一个 txt 文件,然后 post 一些嵌入,如果 txt 文件不存在的话。如果是,那么它将读取文件,检查文件中的日期是否超过 1 分钟前,如果是,它应该发送与创建文件的嵌入相同的嵌入,如果还没有超过 1 分钟,那么它会发送一个嵌入告诉你等待。

出于某种原因,创建和发送方面工作正常,但如果我再次 运行 命令,当它尝试将字符串转换为 DateTime 时失败,显示 "String was not recognized as a valid DateTime."。我检查了多个网站,我使用的日期时间格式是正确的。有什么想法吗?

string FilePath22 = Environment.CurrentDirectory + "/servers/" + Context.Guild.Id + ".txt";
string FilePath = Environment.CurrentDirectory + "/descriptions/" + Context.Guild.Id + ".txt";
string FilePath2 = Environment.CurrentDirectory + "/invites/" + Context.Guild.Id + ".txt";
var chnl = Context.Client.GetChannel(511281184760791056) as ITextChannel;
string invitelink = System.IO.File.ReadAllText(FilePath2);
string desclink = System.IO.File.ReadAllText(FilePath);
var builder2 = new EmbedBuilder()
        .WithColor(Color.Orange)
        .WithAuthor(Context.Guild.Name)
        .WithThumbnailUrl(Context.Guild.IconUrl)
        .WithUrl(invitelink)
        .AddField("Information", "**Owner:** " + Context.Guild.Owner + Environment.NewLine +
        "**Description:** " + Environment.NewLine + Environment.NewLine + desclink + Environment.NewLine + Environment.NewLine + "**Invite:** " + invitelink)
        .AddField("Other Info", "**Members:** " + Context.Guild.MemberCount + Environment.NewLine + "**Emotes:** " + Context.Guild.Emotes.Count + Environment.NewLine + "**Roles:** " + Context.Guild.Roles.Count + Environment.NewLine + "**Created At:** " + Context.Guild.CreatedAt.Date);
        var embed2 = builder2.Build();
        await chnl.SendMessageAsync(embed: embed2);
        var builder44 = new EmbedBuilder()
        .WithColor(Color.Orange)
        .WithTitle("Server Bumped!");
var embed44 = builder44.Build();

if (!File.Exists(FilePath22))
{
    await ReplyAsync(embed: embed44);
    System.IO.File.WriteAllText(FilePath22, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
    return;
}

string readit = System.IO.File.ReadAllText(FilePath22);
Console.WriteLine(readit);
var converted = DateTime.Parse(readit); //problem
Console.WriteLine(converted);
if (HoursPassed(converted))
{
    await ReplyAsync(embed: embed44);
    System.IO.File.WriteAllText(FilePath22, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
    return;
}

var builder10 = new EmbedBuilder()
        .WithColor(Color.Orange)
        .WithTitle("You must wait 24 hours before bumping your server! Try again later.");
var embed10 = builder10.Build();
await ReplyAsync(embed: embed10);

使用DateTime.ParseExact()DateTime.TryParseExact(),例如

DateTime converted;
DateTime.TryParseExact(readit, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out converted);

使用 DateTime.Parse() 如果服务器默认格式与您的格式不同,可能会出现问题。