我正在制作一个音乐播放器。它有两个窗体;一个是主要区域,用于播放音乐。第二个窗体有一个CheckedListBox,您可以在其中选择所需的mp3。 当我点击按钮时,它会将选择保存在.txt文件中,以便我可以在第一个窗体中访问它们,我将把字符串放入音乐播放器路径中以查找文件。
这是我的第二个窗口中的代码,我用它将所选歌曲保存到.txt文件中。
private void selectbtn_Click(object sender, EventArgs e)
{
if (File.Exists(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt"))
{
File.WriteAllText(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt", String.Empty);
}
string[] checkedtitles = new string[checkedListBox1.CheckedItems.Count];
for (int ii = 0; ii < checkedListBox1.CheckedItems.Count; ii++)
{
checkedtitles[ii] = checkedListBox1.CheckedItems[ii].ToString();
}
string selectedSongs = String.Join(Environment.NewLine, checkedtitles);
songRecord.writeRecord(selectedSongs); //I initialised the class containing streamwriter/reader, and called it songRecord
this.Close();
}
无论何时我关闭程序并再次打开它,都无法重写/清除.txt文件。 它只会添加到现有文件中。 我做错了什么吗?这是我的streamreader/writer代码。 我很确定在运行后也关闭了它,但也许有人可以找出问题所在:
namespace songss
{
class DataRecord
{
public void writeRecord(string line)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found.");
}
catch (IOException)
{
Console.WriteLine("Error: IO");
}
catch(Exception)
{
throw;
}
finally
{
if (sw != null)
sw.Close();
}
}
public void readRecord()
{
StreamReader sr = null;
string myInputline;
try
{
sr = new StreamReader(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt");
while ((myInputline = sr.ReadLine()) != null) ; //readline reads whole line
Console.WriteLine(myInputline);
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found");
}
catch(IOException)
{
Console.WriteLine("Error: IO");
}
catch (Exception)
{
throw;
}
finally
{
if (sr != null)
sr.Close();
}
}
}
}
songRecord.writeRecord
做了什么?如果在清除文件之前打开它,它可能已经读入了当前的文本。 - RobFile.WriteAllText
应该替换内容。如果没有替换,请提交错误报告。 - Hubert Grzeskowiak