首页 > 编程语言 >【C#】bin文件、任意类型文件操作汇总

【C#】bin文件、任意类型文件操作汇总

时间:2022-09-26 16:25:03浏览次数:72  
标签:bin 文件 fs string C# res FileStream new

一、bin文件

1、读写

 /// <summary>
        /// 加载任意二进制文件
        /// </summary>
        public static bool LoadBinaryFile(ref WaveData_Class testObj, string Fliepath)
        {
            bool res = false;
            try
            {
                FileStream load_read = File.Open(Fliepath, FileMode.Open, FileAccess.Read, FileShare.None);
                BinaryFormatter bf = new BinaryFormatter();
                testObj = bf.Deserialize(load_read) as WaveData_Class;
                load_read.Close();
                res = true;
            }
            catch (System.Exception ex)
            {
                res = false;
                MessageBox.Show(ex.ToString());
            }
            return res;
        }

        /// <summary>
        /// 存储任意二进制文件文件
        /// </summary>
        public static bool BinaryFileSave(WaveData_Class testObj, string Fliepath)
        {

            bool res = false;
            try
            {
                FileStream save_write;
                save_write = File.Open(Fliepath, System.IO.FileMode.OpenOrCreate);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(save_write, testObj);
                save_write.Close();
                res = true;
            }
            catch (System.Exception ex)
            {
                res = false;
                MessageBox.Show(ex.ToString(), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return res;
        }

 

 

二、任意类型文件

1、读写

string sAllTVData = "";   //要写入文件里的内容变量
                FileStream fs = new FileStream("D://tempdata.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);  //创建文件对象
                StreamReader reader = new StreamReader(fs, System.Text.Encoding.UTF8);   //创建文件读取流对象
                string s_TVinfo = "";
                while ((s_TVinfo = reader.ReadLine()) != null)   //实际工作中对写入文件的内容处理,我遇到的是把文件里的内容读出来,然后结合当前手里的数据进行分析处理,然后重新写入文件里,当然不需要这种需求,就只单纯打开文件,写入文件就行了
                {
                    //sAllTVData = sAllTVData + s_TVinfo +"\n";
                    //sTVDataSum++;
                }
                string data = "sn=" + _uScanCode + "&workOrderCode=" + sWorkOrderCode + "&lanMac=" + _sRecieveLanMac + "&wifiMac=" + _sRecieveWifiMac + "&btMac=" + _sRecieveBtMac + "&testUserName=" + sTestUser + "&testDateTime=" + sTimeStr;
                sAllTVData = data;
                StreamWriter writer = new StreamWriter(fs, System.Text.Encoding.UTF8);   //创建写入文件流对象,指定文件对象和编码字符集
                writer.Write(sAllTVData);   //将内容写入文件,默认是覆盖
                writer.Write(System.Environment.NewLine);  //给写入文件内容后添加换行
                //关闭所有打开的文件流对象
                writer.Close();
                reader.Close();
                fs.Close();

或:

public void TestWrite()
        {
            string FileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".data";

           FileStream DataFile = File.Open(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

            int num = 1000;
            byte[] writebuff = new byte[num];
            for (int h = 0; h < num; h++)
            {
                writebuff[h] = (byte)(h + 1);
            }
            DataFile.Seek(DataFile.Length, SeekOrigin.Begin);
            DataFile.Write(writebuff, 0, num);
            DataFile.Flush();
        }

        public string TestLoad(string path)
        {
            int length = 0;
            string str = "";
            try
            {
                FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                length = (int)fs.Length;
                byte[] readbuf = new byte[length];
                fs.Seek(0, SeekOrigin.Begin);
                fs.Read(readbuf, 0, length);
                for (int i = 0; i < length; i++)
                {
                    str += readbuf[i].ToString() + "  ";
                }
                fs.Close();
                return str;
            }
            catch
            {
                return null;
            }
        }

https://blog.csdn.net/qq_21381465/article/details/80016740

标签:bin,文件,fs,string,C#,res,FileStream,new
From: https://www.cnblogs.com/Mars-0603/p/16731320.html

相关文章

  • docker部署kafka
    version:"3"services:zookeeper:image:'bitnami/zookeeper:latest'ports:-'2181:2181'environment:-ALLOW_ANONYMOUS_LOGIN=yes......
  • 封装配置文件,读取配置文件
    #封装配置文件fromconfigparserimportConfigParserimportosfromCommon.handle_pathimportconf_dirfile_path=os.path.join(conf_dir,'config.ini')class......
  • some code 2 rust
    externcratetokio;pubmoddatatable;pubmodhandle_error;pubmodcommon;usechrono::prelude::*;usechrono::offset::LocalResult;usedatafusion::arrow:......
  • 备战面试day01-二进制/字节码文件以及虚拟机跨平台原理
    什么是二进制文件?二进制是机器码,由01组成,能被机器识别的机器指令。可以被CPU直接执行什么是字节码文件?字节码文件是.class作为后缀名的文件,是介于j......
  • C/C++ x86-64的调用约定,忽略__stdcall、__cdecl、__fastcall、_thiscal
    在设计调用约定时,x64体系结构利用机会清除了现有Win32调用约定(如__stdcall、__cdecl、__fastcall、_thiscall等)的混乱。在Win64中,只有一个本机调用约定而__cdecl......
  • TCP 5连问,你能抗到第几轮?
    1,TCP3次握手具体过程2,请聊聊SYN攻击3,CLOSE-WAIT和TIME-WAIT的作用4,TCP如何保证可靠性5,TCP如何进行拥塞控制答案解析​ TCP是面向连接的通信协议,通过三次握手建立连......
  • Calendar:n天前,n个月前,n个年前
    为了删除无用或者时间过长的日志,需要根据日志的名称获取日志信息。而日志的名称往往和日期相关联,如log-20220926,类似以日期为后缀,如何判断日志与当前日期的关系,使用到Calan......
  • SCPNet: Spatial-Channel Parallelism Network for Joint Holistic and Partial Perso
    摘要:完整图像的行人重识别在过去几年里获得了广泛研究并取得了长足的进步。然而,在现实场景中,行人往往会被物体或他人遮挡,造成partial的行人识别变得困难。本文提出了空间维......
  • JavaScript超大文件上传和断点续传的实现
    ​ 1 背景用户本地有一份txt或者csv文件,无论是从业务数据库导出、还是其他途径获取,当需要使用蚂蚁的大数据分析工具进行数据加工、挖掘和共创应用的时候,首先要将本地文......
  • 【C#】CSV文件操作汇总
    一、读写///<summary>///保存到csv///</summary>publicstaticvoidSaveCsv(stringPath,string[]strArr){......