如果文件已经存在,如何覆盖?

How To Overwrite A File If It Already Exists?

我正在制作音乐播放器。它有两种形式;一个是您播放音乐的主要区域。第二种形式有一个 CheckedListBox,您可以在其中 select 您想要的 mp3。 当我单击一个按钮时,它会将 selection 保存在一个 .txt 文件中,这样我就可以在第一种形式中访问它们,我将在其中将字符串放入音乐播放器查找文件的路径中。

这是我第二种形式的代码,我将 selected 歌曲保存到 .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();   
}

问题是,每当我关闭程序并再次打开它时,我无法 rewrite/clear .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();
        }
    }
    }
    }

WriteAllText

File.WriteAllText应该做你想做的。

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

StreamWriter

StreamWriter class 还有一个选项 overwrite/append:

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to.

public StreamWriter(
    string path,
    bool append
)

示例:

using (StreamWriter writer = new StreamWriter("test.txt", false)){ 
    writer.Write(textToAdd);
}

查看您的代码,您正在传递 true,这意味着追加。

sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);

.NET Compact Framework

如果您遇到不支持任何内容(例如紧凑框架)的 .NET 版本,您也可以自己实现 WriteAllText

static void WriteAllText(string path, string txt) {
    var bytes = Encoding.UTF8.GetBytes(txt);
    using (var f = File.Open(path, FileMode.Create)) {
        f.Write(bytes, 0, bytes.Length);
    }
}

使用这个

File.WriteAllText(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt", line);

而不是

sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);

微软提供的解决方案参考此link: (https://msdn.microsoft.com/en-us/library/system.io.file.appendtext(v=vs.110).aspx)

这是附加现有文件的代码:

StreamWriter writer = File.AppendText(Filepath);
writer.WriteLine(content);
writer.Close();