如何在写入之前清除.txt?

时间:2015-05-15 20:28:29

标签: c#

我想删除我的.txt文件 - 行,但重写不正确。带有文本的行被替换,有时会重复。 如何在重写之前清除打开的.txt文件?

FileStream fileStream = new FileStream(textBox3.Text,FileMode.OpenOrCreate,
        FileAccess.ReadWrite, FileShare.None);
        string line = null;
        int line_number = 0;
        int line_to_delete = 12;

        using (StreamReader reader = new StreamReader(fileStream))
        {
            using (StreamWriter writer = new StreamWriter(fileStream))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    line_number++;

                    if (line_number == line_to_delete)
                        continue;

                    writer.WriteLine(line);
                }
            }
        }

在我使用下面的部分代码并且一切正常之前,我想读取并写入同一个文件。

using (StreamReader reader = new StreamReader(@"C:\Users\user\Desktop\my.txt"))
using (StreamWriter writer = new StreamWriter(@"C:\Users\user\Desktop\my2.txt")) 

1 个答案:

答案 0 :(得分:2)

在FileStream构造函数中使用FileMode.Truncate。例如:

FileStream fileStream = new FileStream(textBox3.Text, FileMode.Truncate, FileAccess.ReadWrite, FileShare.None);