.NET之读写文件的方法

        private void btnAscii2Bin_Click(object sender, EventArgs e)
        {
            string sf = Application.StartupPath + @"\wave.bin";
            //实例化一个文件流--->与写入文件相关联
            FileStream fs = new FileStream(sf, FileMode.Create);
            //实例化BinaryWriter
            BinaryWriter bw = new BinaryWriter(fs);
            foreach (var element in _readData)
            {
                var t = ConvertFloatToByte((float) element);
                bw.Write(t);
                //清空缓冲区
                bw.Flush();
            }
            //关闭流
            bw.Close();
            fs.Close();
        }

        private byte[] ConvertFloatToByte(float f)
        {
            float[] nTemp = new float[1];
            nTemp[0] = f;
            byte[] buf = new byte[4];
            Buffer.BlockCopy(nTemp, 0, buf, 0, 4);
            return buf;
        }

        private float ConvertByteToFloat(byte[] data, int Index)
        {
            float[] nTemp = new float[1];

            Buffer.BlockCopy(data, Index, nTemp, 0, 4);

            return nTemp[0];
        }

        private void btnBin2Ascii_Click(object sender, EventArgs e)
        {
            string aFile = Application.StartupPath + @"\wave.txt";
            string bFile = Application.StartupPath + @"\wave.bin";
            var fs = new FileStream(aFile, FileMode.Create, FileAccess.Write);
            var sw = new StreamWriter(fs,Encoding.UTF8);
            List<float> dList = new List<float>();
            try
            {
                var br = new BinaryReader(new FileStream(bFile,FileMode.Open));
                //get file size
                var fileInfo = new FileInfo(bFile);
                var bytes = br.ReadBytes((int)fileInfo.Length);
                for (int i = 0; i < bytes.Length; i+=4)
                {
                    sw.WriteLine(ConvertByteToFloat(bytes,i));
                    //dList.Add(ConvertByteToFloat(bytes, i));
                    
                }
                sw.Close();
                br.Close();
                fs.Close();
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message + "\n Cannot open file.");
                return;
            }
        }




参考:http://www.cnblogs.com/blsong/archive/2010/10/10/1847063.html

另外,关于FileStream和StreamWriter/StreamReader的区别,参考如下博客

http://www.cnblogs.com/lyd2016/p/6599550.html


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值