C#读取文件

private void button2_Click(object sender, EventArgs e)
{
    string file = "";
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
    openFileDialog.Filter = "Html|*.html|Mht|*.mht|htm|*.htm";
    openFileDialog.RestoreDirectory = true;
    openFileDialog.FilterIndex = 1;
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        file = openFileDialog.FileName;


        //string fileContent = File.ReadAllText(file, Encoding.Default);//第一种方式

 

        //第二种方式
        string strLine = "";
        using (System.IO.StreamReader sr = new System.IO.StreamReader(file,Encoding.Default))
        {                   
            strLine = sr.ReadToEnd();
        }
        //System.Console.WriteLine(strLine);
        this.textBox1.Text = strLine;
    }

}

 

读出来的有可能出出现乱码,这个主要是跟编码格式有关,可以尝试去设置Encoding的属性去修改编码格式。

你可能感兴趣的:(读取文件)