C# 文字檔輸出入及編碼

目的:讀一般的文字檔




private void button2_Click(object sender, EventArgs e)
{
    StringBuilder sb = new StringBuilder();

    FileStream fs = new FileStream(@"C:\VS2012\News1.txt", FileMode.Open, FileAccess.Read);
    /*
    //傳統的寫法,一個一個字讀
    int bb=-1;
    while ((bb = fs.ReadByte()) != -1)
    {
        //fs讀進來的每一個「字」,都給bb
        //當bb是-1時,表示讀到底了,跳出迴圈
                
        char c = (char)bb;
        //將bb轉成字元
                
        sb.Append(c);
    }
    fs.Close();

    textBox1.Text = sb.ToString();
    */

    StreamReader sr = new StreamReader(fs);
    while (!sr.EndOfStream)
        sb.Append(sr.ReadLine()).Append("\r\n");
    //不是結尾時,一次一行的讀
            
    textBox1.Text = sb.ToString();

    //textBox1.Text = sr.ReadToEnd();
    //這最屌,一次就讀到底了
}



目的:讀文字檔,用不同的編碼方式來讀


private void button5_Click(object sender, EventArgs e)
{
    StringBuilder sb = new StringBuilder();

    //FileStream fs = new FileStream(@"C:\VS2012\簡字檔.txt", FileMode.Open, FileAccess.Read);            
    //StreamReader sr = new StreamReader(fs,Encoding.GetEncoding("gb2312"));

    FileStream fs = new FileStream(@"C:\VS2012\日文檔.txt", FileMode.Open, FileAccess.Read);            
    StreamReader sr = new StreamReader(fs,Encoding.GetEncoding(932));
    //注意這邊的編碼方式
    while (!sr.EndOfStream)
        sb.Append(sr.ReadLine()).Append("\r\n");
    sr.Close();
    fs.Close();
    textBox1.Text = sb.ToString();
}



目的:列印出所有的編碼方式



private void button6_Click(object sender, EventArgs e)
{
    StringBuilder sb = new StringBuilder();
    foreach(EncodingInfo ei in Encoding.GetEncodings())
    {
        sb.Append(ei.CodePage).Append("\t")
            .Append(ei.Name).Append("\t")
            .Append(ei.DisplayName).Append("\r\n");
    }

    textBox1.Text = sb.ToString();

}


目的:輸出新的文字檔


private void button7_Click(object sender, EventArgs e)
{
    FileStream fs = new FileStream(@"C:\VS2012\新日文檔.txt", FileMode.Create, FileAccess.Write);
    StreamWriter sw = new StreamWriter(fs);
    sw.Write(textBox1.Text);
    sw.Flush();
    //洗掉緩衝區
    sw.Close();
    fs.Close();

    MessageBox.Show("儲存成功!");
}

留言

熱門文章