我要读取和写入文本文件,主要是现有的方法读取中文时会显示乱码private string file_get_contents(string path)
        {
            string a="";
            StreamReader sr = File.OpenText(path);
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                a += s;
            }
            return a;
        }另外,请问哪里可以查到常用C#操作的代码?谢谢!

解决方案 »

  1.   

    string path = @"c:\MyTest.txt";string str="";
    using (StreamReader sr = new StreamReader(path,System.Text.Encoding.GetEncoding("GB2312"))) 
    {
    str=sr.ReadToEnd();
    }
      

  2.   

    private string file_get_contents(string path)
    {
                string a="";
                StreamReader sr = File.OpenText(path);
                using (StreamReader sr = new StreamReader(path,System.Text.Encoding.GetEncoding ("GB2312"))) 
               {
                   string s = "";
                   while ((s = sr.ReadLine()) != null)
                   {
                       a += s;
                   }
               }            
               return a;
    }
      

  3.   

    private string file_get_contents(string path)
    {
    StringBuilder s=new StringBuilder();
    using (StreamReader sr = new StreamReader(path,System.Text.Encoding.GetEncoding ("GB2312"))) 
    {
    while (sr.ReadLine()!= null && sr.ReadLine().ToString()!="")
    {
    s.Append(sr.ReadLine());
    }
    }            
    return s.ToString();
    }--------------
    using System.Text;
    using System.IO;
      

  4.   

    private string file_get_contents(string path)
    {
          StreamReader sr = new StreamReader(path, System.Text.Encoding.GetEncoding("GB2312"));
          return sr.ReadToEnd();
    }
    如果这样没有sr.Close()的话,系统会自动回收内存,是吧?
    这里的using是什么意思?谢谢!
      

  5.   

    你这样用using的话,好处是过程完之后资源就自动释放掉了
      

  6.   

    using的意思是出了{}范围时,系统会释放其占用的资源