我想知道,如何使用FileStream,StreamReader,StreamWriter这种方式来打开一个TXT文件,当然文件事先有内容格式如下:
   精舞门 罗志祥
   漂移 周杰伦
   四面楚歌 周杰伦
我想要打开这个文件,然后把某一行删除掉,再把删除后的结果写会源文件,求指教!

解决方案 »

  1.   

    List<string> lst=List<String>(File.ReadAllLines(""));
    var l=from s in lst where !s.Contains("") select s;
    File.WriteAllText("");StreamReader sr = new StreamReader(@"E:\test.txt");
                String content = sr.ReadToEnd();
                sr.Close();
                String[] ss = content.Split(new char[]{'\n','\r'},StringSplitOptions.RemoveEmptyEntries);
                StreamWriter sw = new StreamWriter(@"E:\test.txt");
                for (Int32 i = 0; i < ss.Length; i++)
                {
                    sw.WriteLine(ss[i].Trim('/'));
                }            sw.Close();
      

  2.   

    楼主应该明白了,但是鉴于楼主是新手可能对ling不熟悉,所以你可以把var 1换掉
      

  3.   


       private void test()
            {
                string filePath = "f:\\my.txt";
                StreamReader sr = new StreamReader(filePath);
                string line = "";
                while ((line = sr.ReadLine()) != null)
                {
                    //读取要修改的行内容
                    if (line == "the content of del")
                        break;
                }
                sr.Close();            //写入新内容
                File.AppendAllText(filePath, "the new content");
            }
    //刚好在code咯,就给你写了一小段
      

  4.   

    没,我对数据库最感兴趣了,最先就是学的LinQ
      

  5.   

    1. ReadAllLines
    2. for each 或者 linq 过滤
    3. WriteAllLines
      

  6.   

    还没搞定?
    给你写了个帖子,你看看吧
    源码:using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;namespace testfilestream
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private int numoflines=0;
            private string ofd_filepath = string.Empty;
            List<string> list = new List<string>();
            private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "文本文件(*.txt)|*.txt";
                ofd.Title = "打开文本文件";
                ofd.Multiselect = false;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    ofd_filepath = Path.GetFullPath(ofd.FileName);
                    readtext(ofd.FileName);
                    list_bind_richtextbox();
                }
            }        private void readtext(string filename)
            {
                richTextBox1.Text = string.Empty;
                using (StreamReader sr = new StreamReader(filename, Encoding.Default))
                {
                    while (sr.Peek() > -1)
                    {
                        list.Add(sr.ReadLine());
                    }
                    numoflines = list.Count;
                    sr.Close();
                }
            }
            private void list_bind_richtextbox()
            {
                richTextBox1.Text = "";
                for (int i = 0; i < list.Count; i++)
                {
                    richTextBox1.Text += list[i].ToString() + "\r\n";
                }
            }        private void button1_Click(object sender, EventArgs e)
            {
                if (textBox1.Text.Length < 1)
                {
                    MessageBox.Show("请输入想跳至的行");
                }
                else if (int.Parse(textBox1.Text) > numoflines)
                {
                    MessageBox.Show("错误!你输入的行数大于文本框现有的行数");
                }
                else
                {
                    richTextBox1.SelectionStart = richTextBox1.GetFirstCharIndexFromLine(int.Parse(textBox1.Text) - 1);
                    richTextBox1.SelectionLength = 0;
                    richTextBox1.Focus();
                    richTextBox1.ScrollToCaret();                if (MessageBox.Show("你确定要删除该行数据吗?") == DialogResult.OK)
                    {
                        list.RemoveAt(int.Parse(textBox1.Text)-1);
                        list_bind_richtextbox();
                    }
                }         }        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
            {
                try
                {
                    FileStream fs = new FileStream(ofd_filepath, FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    sw.Flush();
                    // 使用StreamWriter来往文件中写入内容
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);
                    for (int i = 0; i < list.Count; i++) sw.WriteLine(list[i]);
                    //关闭此文件t
                    sw.Flush();
                    sw.Close();
                    fs.Close();
                    MessageBox.Show("保存成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存失败!错误信息:"+ex.ToString());
                }
            }
        }
    }
      

  7.   

    呵呵,1楼的代码好像确实有问题,因为程序报错了,出现了IO异常,我的完整代码是:
    //简单地从从所有播放列表中搜索目标歌曲,并删除
            private void deleteSongs(String song)
            {
                for (int i = 0; i < PlayLists.Items.Count; i++)
                {
                    int index = Convert.ToInt32(PlayLists.Items[i].ToString().Substring(4));
                    fileURL = @"F:\我们的歌\播放列表" + index.ToString() + ".txt";                String record;
                    FileStream fs = null;
                    StreamReader sr = null;
                    StreamWriter sw = null;
                    FileInfo fi = new FileInfo(fileURL);
                    try
                    {
                        fs = new FileStream(fileURL, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                        sr = new StreamReader(fs);
                        sw = new StreamWriter(fs);                    record = sr.ReadLine();
                        while (record != null)
                        {
                            String[] s = null;
                            Char[] spliter = new Char[] { ' ' };
                            s = record.Split(spliter);                        switch (index)
                            {
                                case 1:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray1);
                                    break;
                                case 2:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray2);
                                    break;
                                case 3:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray3);
                                    break;
                                case 4:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray4);
                                    break;
                                case 5:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray5);
                                    break;
                                case 6:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray6);
                                    break;
                                case 7:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray7);
                                    break;
                                case 8:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray8);
                                    break;
                                case 9:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray9);
                                    break;
                                case 10:
                                    deleteSong(fs, sw, sr, s, spliter, record, fileURL, song, recordArray10);
                                    break;
                            }
                            record = sr.ReadLine();
                        }
                    }
                    catch (IOException e)
                    {
                        new SpeechSynthesizer().Speak("对不起,你的程序出现了异常,原因是" + e.ToString());
                    }
                    finally
                    {
                        if (sw != null)
                        {
                            sw.Close();
                        }
                        if (sr != null)
                        {
                            sr.Close();
                        }
                        if (fs != null)
                        {
                            fs.Close();
                        }
                    }
                }
                if (songExist == true)
                {
                    new SpeechSynthesizer().Speak("操作已成功,歌曲" + song + "已经从所有列表中删除");
                }
                else
                {
                    new SpeechSynthesizer().Speak("不好意思,歌曲" + song + "不存在播放列表中");
                }
                this.axWindowsMediaPlayer1.Ctlcontrols.play();
            }        #region 删除歌曲的程序调用函数 deleteSong(String[] s, Char[] spliter, String record, String fileURL, String song, bool songExist)
            private void deleteSong(FileStream fs, StreamWriter sw, StreamReader sr, String[] s, Char[] spliter, String record, String fileURL, String song, ArrayList recordArray)
            {
                if (song == s[0])
                {
                    /*
                    songExist = true;
                    String fileContent = sr.ReadToEnd();
                    char[] split = new Char[] {'\n'};
                    String[] records = fileContent.Split(split);
                    fs.SetLength(0);
                    sw.Write(fileContent);
                    recordArray.Remove(record);
                    MessageBox.Show(fileContent);
                     */
                    List<String> lst = new List<string>(File.ReadAllLines(fileURL));
                    foreach (String deleteRecord in lst)
                    {
                        if (deleteRecord == record)
                            lst.Remove(deleteRecord);
                    }
                    File.WriteAllText(fileURL, lst.ToString());
                        for (int i = 0; i < this.axWindowsMediaPlayer1.currentPlaylist.count; i++)
                        {
                            if (this.axWindowsMediaPlayer1.currentPlaylist.Item[i].ToString() == s[0])
                            {
                                this.axWindowsMediaPlayer1.currentPlaylist.removeItem(this.axWindowsMediaPlayer1.currentPlaylist.get_Item(i));
                            }
                        }
                        //s = record.Split(spliter);
                        new SpeechSynthesizer().Speak("操作已成功,歌曲" + song + "已被删除");
                }
                else
                {
                    new SpeechSynthesizer().Speak("不好意思,您要删除的歌曲不存在播放列表中!");
                }
            }