2011年6月17日 星期五

004-檔案處理使用StreamReader

string msg = "";
string filePath = Application.StartupPath + @"\test.txt";

try
{
    if (File.Exists(filePath))
    {
        using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
        {
            long size = sr.BaseStream.Length;
            int countLine = 0;
            string result = "";

            while (sr.EndOfStream != true)
            {
                result = result + "\n" + sr.ReadLine();
                countLine += 1;
            }

            msg += filePath + size + countLine + result;
            MessageBox.Show(msg);
            sr.Close();
        }
    }
    else
    {
        MessageBox.Show("Error");
    }
}catch(IOException ex)
{
    MessageBox.Show(ex.Message);
}