gpt4 book ai didi

c# - BinaryWriter 不采用替代参数

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:13 24 4
gpt4 key购买 nike

我正在尝试将二进制用户数据写入 .data 文件,对于 bw.Write() 替代品 {0},{1},{2},{3} 不能使用,因为它被误认为成为方法的参数。

是否有解决方法将此数据写入文件,但仍像 Console.Write("Hello {0}", name) 中那样替换变量

当我将鼠标悬停在它显示的错误上时

No overload for method 'Write' takes 5 arguments

public static void WriteUser(String path, String user, String auth, String pass, DateTime date)
{

try
{
BinaryWriter bw = new BinaryWriter(new FileStream("mydata", FileMode.Open));

bw.Write("{0}{\nAuth:{1}\nPass:{2}\nDateCreated:{3}", user, auth, pass, date);
}

catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot write to file.");
return;
}
bw.Close();

}

最佳答案

自己调用string.Format即可:

bw.Write(string.Format("{0}{\nAuth:{1}\nPass:{2}\nDateCreated:{3}", user, auth, pass, date));

尽管如果您使用的是 C# 6,您可以使用内插字符串使这个更干净:

bw.Write($"{user}{{\nAuth:{auth}\nPass:{pass}\nDateCreated:{date}");

请注意,如果您尝试编写文本,我将只使用 StreamWriter - 或者更好的是,只需调用 File.WriteAllText:

public static void WriteUser(String path, String user, String auth, String pass, DateTime date)
{
try
{
File.WriteAllText(
"mydata",
$"{user}{{\nAuth:{auth}\nPass:{pass}\nDateCreated:{date}");
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot write to file.");
return;
}
}

关于c# - BinaryWriter 不采用替代参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36017601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com