Tôi đang tạo một trình phát nhạc. Nó có 2 hình thức; một là khu vực chính nơi bạn chơi nhạc. Hình thức thứ hai có một CheckedListBox nơi bạn chọn các mp3 bạn muốn. Khi tôi nhấp vào một nút, nó sẽ lưu lựa chọn trong một tệp .txt để tôi có thể truy cập chúng ở dạng đầu tiên, nơi tôi sẽ đặt các chuỗi vào đường dẫn cho trình phát nhạc để tìm tệp.Làm thế nào để ghi đè lên một tập tin nếu nó đã tồn tại?
Đây là mã trong biểu mẫu thứ hai của tôi, nơi tôi lưu các bài hát đã chọn vào tệp .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();
}
Vấn đề là, bất cứ khi nào tôi đóng chương trình và mở lại, tôi không thể ghi đè/xóa tệp .txt. Nó chỉ thêm vào tệp hiện có. Có điều gì tôi không làm đúng không?
Đây là mã trình tạo luồng/ghi của tôi. Tôi chắc chắn rằng tôi đóng cửa sau khi chạy quá, nhưng có lẽ ai đó có thể tìm ra những gì là sai:
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();
}
}
}
}
Tại sao bạn không xóa tệp nếu nó tồn tại? – JohanP
«songRecord.writeRecord' của bạn đang làm gì?Nếu bạn đang mở tệp trước khi xóa nó, nó có thể đã đọc trong văn bản hiện tại. – Rob
Theo tài liệu API 'File.WriteAllText' sẽ thay thế nội dung. Nếu không, hãy báo cáo lỗi. –