c# binaryreader之readint32與readint16區別

wisdomone1發表於2012-03-29
//檢測檔案是否存在
            if (File.Exists(file_name))
            {
                Console.WriteLine("檔案:{0}已存在"+file_name);
                File.Delete(file_name);
            }

           //向檔案寫入0至10共11個數字
            FileStream fs = new FileStream(file_name,FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fs);
            for (int i = 0; i < 11; i++)
            {
                //int表示int32,表示32位有符號整數
                //注意是(int)i
                bw.Write((int)i);
            }
            fs.Close();//先關閉內層filestream
            bw.Close();//最後關閉外層binarywriter

            //關閉filestream後變數可以重用
            fs = new FileStream(file_name,FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            //顯示寫入檔案的11個數字
            for (int i = 0; i < 11; i++)
            {
                try
                {
                //int32相當於我們常見的整數1,2,3,5等數字,要是int16就會變樣了或者int64也會變樣
                Console.WriteLine(br.ReadInt32());
                }
                catch(EndOfStreamException eof)
                {
                    Console.WriteLine(eof.Message);
                }
            }
            br.Close();
            Console.ReadKey();

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-719789/,如需轉載,請註明出處,否則將追究法律責任。

相關文章