我想用C#将一行行数据(textbox)里边的写入到记事本,然后在把数据从记事本中读出来写到一个listbox中,请问应该怎样写,能否给出关键代码,急用,先谢谢了

解决方案 »

  1.   

    用StreamWriter和StreamReader,一个读,一个写,而且这两个类读写效率高!
      

  2.   

    用StreamWriter和StreamReader  我就用这种
      

  3.   


    using System.io;fileStream fs=new fileStream ("yourtxt.txt",fileMode.Create);
    StreamWirte sw=new StreamWirte (fs);
    sw.WriteLine(textbox.Text);
    sw.Close();
    fs.Close();
    using System.io;fileStream fs=new fileStream ("yourtxt.txt",fileMode.Open);
    StreamRead sr=new StreamRead (fs);
    sr.ReadLine(listbox.Text);
    sr.Close();
    fs.Close();重要的部分  这代码.不出来  我大小写没有注意  你注意下~
      

  4.   

    using System.IO;//写入
    StreamWriter sw = new StreamWriter( @"C:\temp123.txt");
    sw.WriteLine("----------------hello----------------");
    sw.WriteLine("内容");
    sw.WriteLine("----------------hello----------------");
    sw.Flush();
    sw.Close();//读取
    System.IO.StreamReader st;
    st = new System.IO.StreamReader(@"C:\temp123.txt", System.Text.Encoding.UTF8);//UTF8为编码
    this.textBox1.Text = st.ReadToEnd();
      

  5.   

    StreamWriter sw = new StreamWriter( @"C:\temp123.txt",true);
    后边参数为true就是 有新数据继续写
    要是为false 就是 后边的数据覆盖前边的
      

  6.   

    我现在要从文件里读取多行添加到listbox里边,我用StreamReader sr=new StreamReader(、、、、、)string ss=sr.ReadLine(); this.listBox1.Items.add(ss),只能将一行数据插入到listbox中,请问应该怎样将所有的添加到listbox中
      

  7.   

     他们都把代码贴出来了,你google一下一大堆.
    我也是用的StreamWriter和StreamReader
      

  8.   

            while (sr.EndOfStream == false)
            {
                 string ss=sr.ReadLine(); 
                 this.listBox1.Items.add(ss);
            }
      

  9.   


    while(!sr.EndOfStream)
    {
        this.listBox1.Items.Add(sr.ReadLine());
    }
      

  10.   

    //把取到的内容写到文件里去,AppDomain.CurrentDomain.BaseDirectory具有将文本内容读取和写入的功能
                    FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "table.txt", FileMode.OpenOrCreate);
                    fs.Flush();
                    fs.Close();
                    //写入数据
                    StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "table.txt", false, Encoding.Default);
      

  11.   

    用StreamWriter和StreamReader  
      

  12.   

            private void WriteFile(string filepath,string str )
            {            FileStream fs = (!File.Exists(filepath)) ? new FileStream(filepath, FileMode.Create) : File.Open(filepath, FileMode.Append);
                //获得字节数组
                byte[] data = new UTF8Encoding().GetBytes(str+'\n');
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();
            }//调用WriteFile(@"c:\ss.txt","给我分啊")
      

  13.   

    写入oFileStream = new FileStream("文件路径", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
    StreamWriter oStreamWriter = new StreamWriter(oFileStream, Encoding.Default);
    oStreamWriter.Write("要写入内容");
    oStreamWriter.WriteLine();
    oStreamWriter.Close();
    oFileStream.Close();
    读取oFileStream = new FileStream("文件路径", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
    StreamReader oStreamReader = new StreamReader(oFileStream, Encoding.Default);
    string _Text = oStreamReader.ReadToEnd();
    oStreamReader.Close();
    oFileStream.Close();
      

  14.   

    上面有误
    读取时应是FileMode.Open,FileAccess.Read
    唉直接把上面的写入的复制下来了。
      

  15.   

    我觉的你好麻烦啊 对文件操作是很浪费资源的 写进去再读出来 你可以将写进去的内容保存在一个变量中 然后直接赋值给listbox就好了啊 这样就不用再二次读出来了 同时 你把内容再写进记事本里就好了 代码网上多的是 你可以去百度
      

  16.   

    void File.WriteAllText(filepath, content)
    string[] File.ReadAllLine(filepath)
      

  17.   

    /// <summary>
            /// 写数据到文件
            /// </summary>
            /// <param name="strDataList">行数据列表</param>
            /// <param name="filename">文件名</param>
            /// <returns>是否成功</returns>
            public static bool WriteToFile(List<string> strDataList,string filename)
            {
                try
                {                //Pass the filepath and filename to the StreamWriter Constructor
               //     StreamWriter sw = new StreamWriter(filename);
                    StreamWriter sw = new StreamWriter(filename,false,Encoding.GetEncoding("gb2312"));                sw.Write("", false);                //Write a line of text
                    foreach (string item in strDataList)
                    {
                        sw.WriteLine(item, true);
                    }                //Close the file
                    sw.Close();
                    return true;
                }
                catch (Exception e)
                {
                    return false;
                }
            }        /// <summary>
            /// 从文件获取数据
            /// </summary>
            /// <param name="fileName">文件名</param>
            /// <returns>行数据列表</returns>
            public static List<string> ReadFromFile(string fileName)
            {
                List<string> dataList = new List<string>();
                String line;
                try
                {
                    //Pass the file path and file name to the StreamReader constructor
                    StreamReader sr = new StreamReader(fileName, Encoding.GetEncoding("gb2312"));                //Read the first line of text
                    line = sr.ReadLine();                //Continue to read until you reach end of file
                    while (line != null)
                    {
                        dataList.Add(line);
                        //Read the next line
                        line = sr.ReadLine();
                    }                //close the file
                    sr.Close();
                }
                catch (Exception e)
                {
                    dataList = null;
                }
                return dataList;
            }
      

  18.   

    //检查文件是否存在
    if (!File.Exists(filepath)) return null;
    //读起文件流
    FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Read);
    StreamReader m_streamRead = new StreamReader(fs, System.Text.Encoding.Default);
    m_streamRead.BaseStream.Seek(0, SeekOrigin.Begin);
    string s = m_streamRead.ReadToEnd();
    m_streamRead.Close();
    fs.Close();
    string[] sList=s.Split('\n');//再把数组给List绑定
      

  19.   

    问题全解决了在给分啊我现在想把文件中的数据读入到一个datagrid中,请问应该怎样写进datagrid中呢,文件中的数据是三列,且每一列之间用“,”隔开,如“78,文件,时间”。并且这个文件没有格式
      

  20.   

    using System.io;fileStream fs=new fileStream ("yourtxt.txt",fileMode.Create);
    StreamWirte sw=new StreamWirte (fs);
    sw.WriteLine(textbox.Text);
    sw.Close();
    fs.Close();
    上面是写入下面上读取到ListBox
    fileStream fs=new fileStream ("yourtxt.txt",fileMode.Open);
    StreamRead sr=new StreamRead (fs);
    listbox.text=sr.ReadToEnd()
    sr.Close();
    fs.Close();
      

  21.   

    如果是 ini格式的配置文件可以这样        [DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
            //参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。C#申明INI文件的读操作函数GetPrivateProfileString(): 
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
            //参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称。
    写入、读取WritePrivateProfileString(Section,Key,Value,this.inipath);//写入        public string IniReadValue(string Section,string Key)//度取
            {
               StringBuilder temp = new StringBuilder(200);
              int i = GetPrivateProfileString(Section,Key,"",temp,200,this.inipath);
              return temp.ToString();
            }
    文件格式如下:
    [段落名1]
    关键字1=值1
    关键字2=值2
    关键字3=值3
    [段落名2]
    关键字1=值1
    关键字2=值2
      

  22.   

    给你参考参考吧   /// <summary>
            /// 将存贮在文本文件中的数据绑定到DropDownList中  test,test
            /// </summary>
            /// <param name="drdlst">下拉菜单</param>
            /// <param name="filePath">虚拟路径</param>
            public void Drdlst_BindDataByTxt1(DropDownList drdlst, string filePath)
            {
                string fileName = HttpContext.Current.Server.MapPath(filePath);
                string content = "";
                StreamReader sr = null;
                try
                {
                    //打开文件并显示其内容
                    sr = new StreamReader(fileName, System.Text.Encoding.Default);
                    for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())
                    {
                        content += line.ToString();
                    }
                    string[] arr = content.Split(',');
                    for (int i = 0; i < arr.Length; i++)
                    {
                        ListItem li = new ListItem();
                        li.Text = arr[i].ToString();
                        li.Value = arr[i].ToString();
                        drdlst.Items.Add(li);
                    }
                }
                catch (IOException ee)
                {
                    HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
                }
                finally
                {
                    if (sr != null)
                    {
                        sr.Close();
                    }
                }
            }        /// <summary>
            /// 获取txt中信息
            /// </summary>
            /// <param name="filePath">虚拟路径</param>
            /// <returns></returns>
            public string GetTxtInfo(string filePath)
            {
                string fileName = HttpContext.Current.Server.MapPath(filePath);
                string str = "";
                StreamReader sr = null;
                try
                {
                    sr = new StreamReader(fileName, System.Text.Encoding.Default);
                    for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())
                    {
                        str += line.ToString();
                    }
                }
                catch (IOException ee)
                {
                    HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
                }
                finally
                {
                    if (sr != null)
                    {
                        sr.Close();
                    }
                }            return str;
            }        /// <summary>
            /// 保存数据到txt中
            /// </summary>
            /// <param name="str">要保存的数据</param>
            /// <param name="filePath">虚拟路径</param>
            public void SaveTxtInfo(string str, string filePath)
            {
                string fileName = HttpContext.Current.Server.MapPath(filePath);
                StreamWriter sw = null;
                FileStream oFileStream = null;
                try
                {
                    if (!System.IO.File.Exists(fileName))
                    {
                        oFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    }
                    else
                    {
                        oFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                    }                sw = new StreamWriter(oFileStream, Encoding.Default);
                    sw.Write(str);
                    sw.WriteLine();
                }
                catch (IOException ee)
                {
                    HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Close();
                        oFileStream.Close();
                    }
                }
            }
      

  23.   

    StreamWriter和StreamReader  
      

  24.   

    顶一下,再请教一下,如何用程序打开一个PDF文件啊?
      

  25.   

    lz rp真好,这么多人回答而且被推荐了。答案都在上面了,LZ好好消化一下吧。
      

  26.   

    用StreamReader, StreamWriter, 具体使用可以查询msdn.
      

  27.   

    using System.IO;//写入
    StreamWriter sw = new StreamWriter( @"C:\temp123.txt");
    sw.WriteLine("----------------hello----------------");
    sw.WriteLine("内容");
    sw.WriteLine("----------------hello----------------");
    sw.Flush();
    sw.Close();//读取
    System.IO.StreamReader st;
    st = new System.IO.StreamReader(@"C:\temp123.txt", System.Text.Encoding.UTF8);//UTF8为编码
    this.textBox1.Text = st.ReadToEnd();
      

  28.   

    干嘛这么麻烦?直接从文本框里读出来写到列表框里不就行了嘛!!!list1.Items.AddRange(textbox1.Lines); //一句代码就搞定了。
      

  29.   

     using (SrmR = new StreamReader(path, Encoding.GetEncoding("GB2312")))
     {
          while (!SrmR.EndOfStream)
            {
                 ...
            }
     }
      

  30.   

       filestream 文件数据流操作就可以了!
      

  31.   

     //public void WriteSQL(string where)
            //{
            //    return;
            //    string path = "~/Web/Share/SqlLog.txt";
            //    FileStream fs = null;
            //    StreamWriter sw = null;
            //    try
            //    {
            //        if (File.Exists(Server.MapPath(path)))
            //        {
            //            fs = new FileStream(Server.MapPath(path), FileMode.Append);
            //        }
            //        else
            //        {
            //            fs = new FileStream(Server.MapPath(path), FileMode.Create);
            //        }        //        sw = new StreamWriter(fs, System.Text.Encoding.Default);
            //        sw.Write(DateTime.Now.ToString());
            //        sw.Write("\r\n" + where + "\r\n\r\n");
            //    }
            //    catch (Exception e)
            //    {
            //        throw e;
            //    }
            //    finally
            //    {
            //        sw.Close();
            //        fs.Close();
            //    }        //}
      

  32.   

    .net 的帮助里有很多示例代码!!!
      

  33.   

        while (sr.EndOfStream == false) 
            { 
                string ss=sr.ReadLine(); 
                this.listBox1.Items.add(ss); 
            } 
      

  34.   

    再问大家一个问题啊,我如果想把数据写入一个文件,但是目录不确定,不像"C:\temp123.txt", 而是当写入文件时检测磁盘目录,可以把文件放在任何一个目录下谢谢大家的回答,结贴时每个人都有分