2011年6月15日 星期三

002-檔案處理使用BinaryReader

           //設定文字檔存放目錄,Application.StartupPath程式起始的路徑
            string filePath = Application.StartupPath + @"\test.txt";
            string msg = "";

            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                if(File.Exists(filePath))
                {
                    using(BinaryReader br = new BinaryReader(fs))
                    {
                        string result = br.ReadString();//讀取字串
                        long size = br.BaseStream.Length;

                        msg = msg + "檔案位置" + filePath + "\n";
                        msg = msg + "檔案大小" + size + "Bytes \n" + result;
                        MessageBox.Show(msg);
                        br.Close();
                    }
                    fs.Close();
                }else
                {
                    MessageBox.Show("不存在");
                }
            }catch(IOException ex)
            {
                MessageBox.Show(ex.Message);
            }