C# 文件操作

本篇主要记录C#操作文件

相对路径在项目文件...\bin\Debug 目录下

一、写入读取文件

写入
        /// <summary>
        /// initial 文件写入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button1_Click(object sender, EventArgs e)
        {
            //1.创建一个键值对
            Dictionary<String, Dictionary<string, string>> data = new Dictionary<string, Dictionary<string, string>>();
            //2.添加数据源
            data.Add("设备套接字", new Dictionary<string, string>()
            {
                {"ip","192.168.21.11" },
                {"端口","502" }
            });
            //3.写入到本地
            using (StreamWriter streamWriter = new StreamWriter(path,true))
            {
                //4.循环写入
                foreach (string item in data.Keys)
                {
                    //4.1写入键
                    streamWriter.WriteLine($"[{item}]");
                    //5.写入值
                    foreach (string item2 in data[item].Keys)
                    {
                        streamWriter.WriteLine($"{item2}={data[item][item2]}");
                    }

                }
            }
            
        }
      
读取
        /// <summary>
        /// initial 文件读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button2_Click(object sender, EventArgs e)
        {
            Dictionary<String, Dictionary<string, string>> saveData = new Dictionary<string, Dictionary<string, string>>();
            string key = null;

            //配置io流
            using (StreamReader reader = new StreamReader(path,true))
            {
                while (!reader.EndOfStream)
                {
                    //读取
                    string data = reader.ReadLine();
                    //判断是否键
                    if (data.StartsWith("[") && data.EndsWith("]"))
                    {
                        key = data.Substring(1, data.Length - 2);
                        saveData.Add(key,new Dictionary<string, string>());
                    }
                    //判断是否是值
                    else if (!string.IsNullOrEmpty(data) && !data.EndsWith(";"))
                    {
                        int index = data.IndexOf("=");
                        if (index > 0)
                        {
                            //获取值
                            saveData[key].Add(data.Substring(0,index), data.Substring(index+1));
                        }
                    }
                   
                }
               
            }
        }

二、文件的基本操作

目录操作
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button1_Click(object sender, System.EventArgs e)
        {
            //###一.创建文件夹两种路径方式
            //1.相对路径地址,项目输出路径,在../bin/Debug目录下
            Directory.CreateDirectory("log");
            //在创建的目录中创建子目录
            Directory.CreateDirectory("log/zhangsan");

            //2.绝对路径地址,加磁盘符
            //Directory.CreateDirectory("D:\\c#\\source\\test");


            // ###2.判断指定路径下是否有该目录
            if (Directory.Exists("log"))
            {
                MessageBox.Show("存在");
            }

        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button2_Click(object sender, System.EventArgs e)
        {
            //删除目录,删除的目录必须为空,见构造方法
            Directory.Delete("log/zhangsan",true); //删除当前路径目录包括子文件
            //Directory.Delete("log/zhangsan");//删除当前路径目录,有子文件失败
            MessageBox.Show(Directory.Exists("log")?"删除成功":"删除失败");
            
        }

        /// <summary>
        /// 查询子文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button3_Click(object sender, System.EventArgs e)
        {
            //查询目录下的文件,不是文件夹,文件是带后缀名的,例如:111.txt
            string[] files = Directory.GetFiles("log");
            foreach (var item in files)
            {
                MessageBox.Show(item);
            }
        }

 

文件流
 // FileStream: 文件流

        Encoding encoding = Encoding.UTF8;//二进制转换格式
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button4_Click(object sender, System.EventArgs e)
        {
            //第一步:配置文件操作对象
            string path = "opreationLog.txt";
            FileMode fileMode = FileMode.Append;
            FileAccess fileAccess = FileAccess.Write;

            //初始化IO流对象
            FileStream fileStream = new FileStream(path, fileMode, fileAccess);

            //第二步:写入
            //TODO: 注意这里要加入 \r 才能识别保存换行
            byte[] data = encoding.GetBytes($"{textBox1.Text}\r\n");
            fileStream.Write(data,0,data.Length);

            //关闭IO流
            fileStream.Close();

        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button5_Click(object sender, System.EventArgs e)
        {
            //第一步:配置文件操作对象
            string path = "opreationLog.txt";
            FileMode fileMode = FileMode.Open;
            FileAccess fileAccess = FileAccess.Read;

            //初始化IO流对象
            FileStream fileStream = new FileStream(path, fileMode, fileAccess);

            byte[] readBytes = new byte[1024];
            fileStream.Read(readBytes, 0, 1024);
            textBox2.Text = encoding.GetString(readBytes);

            //关闭IO流
            fileStream.Close();
        }

 

序列化
        /// <summary>
        /// 序列化导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button6_Click(object sender, System.EventArgs e)
        {
            //第一步:配置文件操作对象
            string path = "save_person.txt";
            FileMode fileMode = FileMode.Create;
            FileAccess fileAccess = FileAccess.Write;

            // 第二步:配置io流对象
            //using自动管理关闭文件流
            using (FileStream fileStream = new FileStream(path, fileMode, fileAccess))
            {
                //创建序列化对象
                BinaryFormatter binary = new BinaryFormatter();
                //获取表格中的数据
                List<Person> persons = new List<Person>();
                Person person;
                for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
                {
                    person = new Person();
                    person.Id = Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value); 
                    person.Name = dataGridView1.Rows[i].Cells[1].Value.ToString(); 
                    person.Age = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value); 
                    persons.Add(person);
                }
                //开始序列化
                binary.Serialize(fileStream,persons);
            }
        }

        /// <summary>
        /// 序列化导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button7_Click(object sender, EventArgs e)
        {
            //第一步:配置文件操作对象
            string path = "save_person.txt";
            FileMode fileMode = FileMode.Open;
            FileAccess fileAccess = FileAccess.Read;

            // 第二步:配置io流对象
            //using自动管理关闭文件流
            using (FileStream fileStream = new FileStream(path, fileMode, fileAccess))
            {
                //创建序列化对象
                BinaryFormatter binary = new BinaryFormatter();
                //反序列化
                Object obj = binary.Deserialize(fileStream);
                //转换成集合
                List<Person> people = (List<Person>)obj;
                //清理表格上的数据
                dataGridView1.Rows.Clear();
                //循环写入
                foreach (var item in people)
                {
                    dataGridView1.Rows.Add(item.Id, item.Name, item.Age);
                }


            }
        }
    }

    [Serializable]
    class Person
    {
    }

 

三、CSV文件

        /// <summary>
        /// 导入CSV
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button2_Click(object sender, EventArgs e)
        {
            //第一步:配置IO流操作对象
            using (StreamReader streamReader = new StreamReader("产品数据.csv"))
            {
                int index = 0;

                while(!streamReader.EndOfStream)
                {
                    string data = streamReader.ReadLine();
                    string[] str = data.Split(',');
                    //不插入表头
                    if (index > 0)
                    {
                        dataGridView1.Rows.Add(str);
                    }
                    index++;
                }
                

            }
        }

        /// <summary>
        /// 导出CSV
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button1_Click(object sender, EventArgs e)
        {
            //第一步:配置文件流操作对象
            using(StreamWriter streamWrite = new StreamWriter("产品数据.csv",false))
            {
                //加入表头
                streamWrite.WriteLine($"{dataGridView1.Columns[0].HeaderText},{dataGridView1.Columns[1].HeaderText},{dataGridView1.Columns[2].HeaderText}");
                //第二步:循环写入
                for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
                {
                    streamWrite.WriteLine($"{dataGridView1.Rows[i].Cells[0].Value},{dataGridView1.Rows[i].Cells[1].Value},{dataGridView1.Rows[i].Cells[2].Value}");
                }
             
            }
        }

 

四、Excel

       /// <summary>
        /// 导出excel文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button4_Click(object sender, EventArgs e)
        {
            //第一步:配置Excel文件操作对象
            using (XLWorkbook xl = new XLWorkbook())
            {
                //第二步:创建工作页
                IXLWorksheet sheet = xl.AddWorksheet("产品数据页1");
                //第三步:循环添加数据

                //写入表头
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    //注意Cell 必须从1开始,否则报错
                    sheet.Cell(1, i + 1).Value = dataGridView1.Columns[i].HeaderText;
                }

                //写入表格数据
                for (int i = 0; i < dataGridView2.Rows.Count-1; i++)
                {
                    //第四步:获取第i行列的值
                    for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++)
                    {
                        //第五步:写入数据
                        sheet.Cell(i+2,j+1).Value = dataGridView2.Rows[i].Cells[j].Value.ToString();
                    }
                }
                //第六步:保存到本地
                xl.SaveAs("数据.xlsx");
            }
        }

        /// <summary>
        /// 导入Excel文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button3_Click(object sender, EventArgs e)
        {
            //第一步:配置Excel文件操作对象
            using (XLWorkbook xl = new XLWorkbook("数据.xlsx"))
            {
                //第二步:获取第一个sheet页
                IXLWorksheet workbook = xl.Worksheet(1);
                //第三步:获取sheet页中数据
                IXLRow row;
                List<string> list;
                // 从2开始不要表头
                for (int i = 2; i <= workbook.Rows().Count(); i++)
                {
                    row = workbook.Row(i);
                    list = new List<string>();
                    for (int j = 1; j <= row.Cells().Count(); j++)
                    {
                        string data = workbook.Cell(i, j).Value.ToString();
                        list.Add(data);
                    }

                    dataGridView2.Rows.Add(list);
                }
            }
        }

 

posted @ 2024-07-30 16:04  别动我的猫  阅读(40)  评论(0编辑  收藏  举报