[英]Cannot save txt file in c# after loading it
我会尽量使这个简短。 我正在根据自己的意愿制作一个程序,作为视频游戏(Dark Souls II)的实用程序。该程序的部分功能是将角色构建保存到文本文件中,它还可以加载文本文件并用新信息覆盖它们。 它需要将 txt 文件拆分成一个可以在加载文件时修改的数组——这样它就可以将它保存到另一个文件中。 有很多代码,所以我只会发布相关的内容,但它让我在特定位置超出范围,因为它保存文本文件的方式是一条长行,我只能用逗号分隔。
private void btnChar_Click(object sender, EventArgs e)
{
string fullChar = full[0]
+ full[1]
+ full[2]
+ full[3]
+ full[4]
+ full[5]
+ full[6]
+ full[7]
+ full[8]
+ full[9]
+ full[10]
+ full[11]
+ full[12]
+ full[13]
+ full[14]
+ full[15]
+ full[16]
+full[17];
FlexibleMessageBox.Show(fullChar);
}
private void saveCharacterToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text Documents (.txt)|*.txt";
saveFileDialog1.DefaultExt = ".text";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
string fullChar = full[0] + ", "
+ full[1] + ", "
+ full[2] + ", "
+ full[3] + ", "
+ full[4] + ", "
+ full[5] + ", "
+ full[6] + ", "
+ full[7] + ", "
+ full[8] + ", "
+ full[9] + ", "
+ full[10] + ", "
+ full[11] + ", "
+ full[12] + ", "
+ full[13] + ", "
+ full[14] + ", "
+ full[15] + ", "
+ full[16] + ", "
+ full[17] + ", ";
//Save file dialog for saving characters
try
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//Code to write the stream goes here.
File.WriteAllText(saveFileDialog1.FileName, fullChar);
}
}
catch (Exception etc)
{
MessageBox.Show("An error occured: " + etc.Message);
}
}
private void loadCharacterToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Text Documents (.txt)|*.txt";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
string fullChar;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Code to write the stream goes here.
fullChar = openFileDialog1.FileName;
full = fullChar.Split(',');
}
}
如果您不确定完整数组的有效长度(您说 18 个元素或更少),那么您不能盲目地假设您拥有所有 18 个元素。
相反,您可以使用string.Join方法来构建要显示或写入文件的字符串
private void btnChar_Click(object sender, EventArgs e)
{
string fullChar = string.Join(",", full);
FlexibleMessageBox.Show(fullChar);
}
private void saveCharacterToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text Documents (.txt)|*.txt";
saveFileDialog1.DefaultExt = ".text";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
string fullChar = string.Join(", ", full);
//Save file dialog for saving characters
......
}
但错误的真正原因在于应该取回文件内容的代码。 在那里,获得文件名后,您需要阅读它。
实际代码只是尝试拆分文件名。
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fullChar = File.ReadAllText(openFileDialog1.FileName);
full = fullChar.Split(',');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.