我尝试将二进制用户数据写入.data文件,而对于bw.Write(),无法使用替换{0},{1},{2},{3}因为它是误认为是方法的参数。
是否有解决方法将此数据写入文件但仍然替换如Console.Write中的变量(" Hello {0}",name)
当我将鼠标悬停在错误上时
方法没有过载'写'需要5个参数
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();
}
答案 0 :(得分:3)
请自己致电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;
}
}