StreamReader读取ini文件时出现中文乱码

  private System.Windows.Forms.OpenFileDialog ofd;
  private System.Windows.Forms.TextBox textBox1;
  private System.Windows.Forms.Button btnSave;
  private System.Windows.Forms.SaveFileDialog sfd;
  private System.Windows.Forms.Button btnOpen;


  StreamWriter writer;
  StreamReader reader;
  FileStream fs;
  string theFile = @"C:\WINDOWS\system32\KeyValue.ini";
  private void btnOpen_Click(object sender, System.EventArgs e)
  {
   ofd.InitialDirectory=@"C:\WINDOWS\system32";
   //Application.ExecutablePath; //"文本文件(*.txt)|*.txt|*.ini";//
   //ofd.Filter="word Files(*.doc)|*.doc|All Files(*.*)|*.*";
   ofd.FileName = theFile;
   if (ofd.ShowDialog()==DialogResult.OK )
   {     
    try
    {
     fs=new FileStream(theFile,FileMode.Open);
     reader=new StreamReader(fs,System.Text.Encoding.GetEncoding("gb2312"));     
     textBox1.Text=reader.ReadToEnd();     
     reader.Close();
    }
    catch(Exception excep)
    {
     MessageBox.Show(excep.Message);
    }
    finally
    {
     reader.Close();
     fs.Close();
    }
   }
  }

  private void btnSave_Click(object sender, System.EventArgs e)
  {
   //sfd.InitialDirectory=Application.ExecutablePath;
   //sfd.Filter="*.ini";//"word Files(*.doc)|*.doc|All Files(*.*)|*.*";
   sfd.OverwritePrompt=true;
   sfd.FileName = theFile;
   if(sfd.ShowDialog()==DialogResult.OK)
   {
    try
    {
     fs=new FileStream(theFile,FileMode.Create);
     writer=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
     writer.Write(textBox1.Text);
    }
    catch (Exception excep)
    {
     MessageBox.Show(excep.Message);
    }
    finally
    {
     writer.Flush();
     writer.Close();
     fs.Close();
     this.Close();
    }
   }
  }

你可能感兴趣的:(Stream)