如果已经存在,如何覆盖文件? [英] How To Overwrite A File If It Already Exists?

查看:112
本文介绍了如果已经存在,如何覆盖文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做音乐播放器.它有2种形式;一个是您播放音乐的主要区域.第二种形式有一个CheckedListBox,您可以在其中选择所需的mp3.当我单击一个按钮时,它将选择内容保存到一个.txt文件中,这样我就可以以第一种形式访问它们,将字符串放入音乐播放器的路径中以查找文件.

I'm making a music player. It has 2 forms; one is the main area where you play music. The second form has a CheckedListBox where you select the mp3s you want. When I click a button, it saves the selection in a .txt file so I can access them in the first form, where I'll put the strings into the paths for music player to find the files.

这是第二种形式的代码,我将选定的歌曲保存到.txt文件中.

This is the code in my second form, where I save the selected songs into .txt files.

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文件.它只是添加到现有文件上.有什么我做不对的事情吗?

The problem is, whenever I close the program and open it again, I can't rewrite/clear the .txt file. It just adds on to the existing file. Is there something I'm not doing right?

这是我的流阅读器/编写器代码.我很确定我也可以在运行后将其关闭,但也许有人可以找出问题所在:

Here is my streamreader/writer codes. I'm pretty sure I closed it after running too, but perhaps somebody can figure out what's wrong:

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 应该可以你想要什么.

WriteAllText

File.WriteAllText should do what you want.

创建一个新文件,将指定的字符串写入该文件,然后关闭文件.如果目标文件已经存在,则将其覆盖.

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类也具有覆盖/添加选项:

StreamWriter

The StreamWriter class also has an option to overwrite/append:

为指定的实例初始化StreamWriter类的新实例使用默认的编码和缓冲区大小的文件.如果文件存在,它可以被覆盖或附加.

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 ,这意味着追加.

Looking at your code, you're passing in true which means append.

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);
    }
}

这篇关于如果已经存在,如何覆盖文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆