【发布时间】:2017-10-29 08:40:22
【问题描述】:
我正在制作音乐播放器。它有两种形式;一个是您播放音乐的主要区域。第二种形式有一个 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 文件。它只是添加到现有文件中。是不是我做的不对?
这是我的流式读取器/写入器代码。我很确定我在运行后也关闭了它,但也许有人可以找出问题所在:
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在做什么?如果您在擦除之前打开文件,它可能已经读入当前文本。 -
根据 API 文档
File.WriteAllText应该替换内容。如果没有,请提交错误报告。 -
这是清除文件的代码。请将写入列表的代码粘贴到文件中。该部分包含错误。我很确定您可能没有关闭流编写器或文件。这就是为什么文件被锁定的原因,第二次尝试写入时,之前的锁定状态没有清除并导致问题。
-
调试你的代码。并通过暂停来检查文件是否正在被清除。然后弄清楚是什么添加了内容。
标签: c# .net winforms text-files streamwriter