[英]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.