C#(四十六)之基于流的文件操作(FileStream)

这篇具有很好参考价值的文章主要介绍了C#(四十六)之基于流的文件操作(FileStream)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

FileStream类属性和方法

属性

CanRead 指示当前文件流是否支持读取

CanWrite 指示当前文件流是否支持写入

CanSeek 指示当前文件流是否支持查找

IsAsync FileStream是同步打开还是异步打开

Length 流的长度(字节数)

CanTimeOut 当前文件流是否可以超时

ReadTimeOut 最大读取时间,超过则超时
WriteTimeOut 最大写入时间,超过则超时

方法

Read() 从文件中读取字节块

ReadByte() 从文件中读取一个字节

Write() 将字节块写入文件

WriteByte() 将一个字节写入文件

Seek() 设置当前流的位置

Close() 关闭当前流并释放与之关联的资源

Dispose(): 释放由 Stream 使用的所有资源

FileStream同样使用命名空间System.IO

将创建文件流对象的过程写在using当中,会自动的帮助我们释放流所占用的资源。

FileStream类相关的枚举

FileMode:Append、Create、CreateNew、Open、OpenOrCreate、Truncate(切除)

FileAccess:Read、ReadWrite、Write

FileShare:Inheritable(使文件的句柄可由子进程进行继承)、None、Read、ReadWrite、Write

写入文件:

public static string filePath = @"F:codeFileStreams.txt";
        public FileStream ff = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        public string sss = "";
        /// <summary>
        /// 创建文件并写入
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            string filePath = @"F:codeFileStreams.txt";
            FileStream ff = new FileStream(filePath,FileMode.OpenOrCreate,FileAccess.ReadWrite);
            string content = @richTextBox1.Text;
            // 将字符串读入字节数组中。
            byte[] buffer = Encoding.Default.GetBytes(content);
            // 将数组写入文件
            ff.Write(buffer, 0, buffer.Length);
            ff.Close();
            MessageBox.Show("写入成功");
        }

文件读取:

/// <summary>
        /// 读取文件
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            if (sss == "")
            {
                byte[] buffer = new byte[1024 * 1024 * 2];    //定义一个2M的字节数组
                //返回本次实际读取到的有效字节数
                int r = ff.Read(buffer, 0, buffer.Length);    //每次读取2M放到字节数组里面
                //将字节数组中每一个元素按照指定的编码格式解码成字符串
                sss = Encoding.Default.GetString(buffer, 0, r);
                label1.Text = sss;
                // 关闭文件流
                ff.Close();
                // 关闭资源
                ff.Dispose();
 
            }
            else
            {
                MessageBox.Show("请不要重复点击");
            }
           
        }

复制文件:

/// <summary>
        /// 使用FileStream复制文件
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            string oldPath = @"F:视频教程曾瑛C#视频教程合集(111课程)zy1.flv";
            string newPath = @"D:qqqqqqq.flv";
            CopyFile(oldPath, newPath);
            MessageBox.Show("复制成功");
        }
        /// <summary>
        /// 自定义文件复制函数
        /// </summary>
        public static void CopyFile(string source,string target)    
        {
            //创建负责读取的流
            using (FileStream fsread = new FileStream(source, FileMode.Open, FileAccess.Read))
            {
                //创建一个负责写入的流
                using (FileStream fswrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buffer=new byte[1024*1024*5];    //声明一个5M大小的字节数组
                    //因为文件不止5M,要循环读取
                    while(true)
                    {
                        int r=fsread.Read(buffer, 0, buffer.Length);    //返回本次实际读取到的字节数
                        //如果返回一个0时,也就意味着什么都没有读到,读取完了
                        if(r==0)
                            break;
                        fswrite.Write(buffer,0,r);
                    }
                    
               }
            }
        }
 

测试使用全部代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
 
namespace FileStreams
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        public static string filePath = @"F:codeFileStreams.txt";
        public FileStream ff = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        public string sss = "";
 
        /// <summary>
        /// 创建文件并写入
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            string filePath = @"F:codeFileStreams.txt";
            FileStream ff = new FileStream(filePath,FileMode.OpenOrCreate,FileAccess.ReadWrite);
            string content = @richTextBox1.Text;
            // 将字符串读入字节数组中。
            byte[] buffer = Encoding.Default.GetBytes(content);
            // 将数组写入文件
            ff.Write(buffer, 0, buffer.Length);
            ff.Close();
            MessageBox.Show("写入成功");
        }
        /// <summary>
        /// 读取文件
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            if (sss == "")
            {
                byte[] buffer = new byte[1024 * 1024 * 2];    //定义一个2M的字节数组
                //返回本次实际读取到的有效字节数
                int r = ff.Read(buffer, 0, buffer.Length);    //每次读取2M放到字节数组里面
                //将字节数组中每一个元素按照指定的编码格式解码成字符串
                sss = Encoding.Default.GetString(buffer, 0, r);
                label1.Text = sss;
                // 关闭文件流
                ff.Close();
                // 关闭资源
                ff.Dispose();
 
            }
            else
            {
                MessageBox.Show("请不要重复点击");
            }
           
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
 
        }
        /// <summary>
        /// 使用FileStream复制文件
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            string oldPath = @"F:视频教程曾瑛C#视频教程合集(111课程)zy1.flv";
            string newPath = @"D:qqqqqqq.flv";
            CopyFile(oldPath, newPath);
            MessageBox.Show("复制成功");
        }
        /// <summary>
        /// 自定义文件复制函数
        /// </summary>
        public static void CopyFile(string source,string target)    
        {
            //创建负责读取的流
            using (FileStream fsread = new FileStream(source, FileMode.Open, FileAccess.Read))
            {
                //创建一个负责写入的流
                using (FileStream fswrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buffer=new byte[1024*1024*5];    //声明一个5M大小的字节数组
                    //因为文件不止5M,要循环读取
                    while(true)
                    {
                        int r=fsread.Read(buffer, 0, buffer.Length);    //返回本次实际读取到的字节数
                        //如果返回一个0时,也就意味着什么都没有读到,读取完了
                        if(r==0)
                            break;
                        fswrite.Write(buffer,0,r);
                    }
                    
               }
            }
        }
    }
}
 

 

Form1.designer.cs

namespace FileStreams
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows 窗体设计器生成的代码
        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.button2 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(12, 102);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(122, 35);
            this.button1.TabIndex = 0;
            this.button1.Text = "创建文件并写入";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // richTextBox1
            //
            this.richTextBox1.Location = new System.Drawing.Point(13, 13);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(121, 83);
            this.richTextBox1.TabIndex = 1;
            this.richTextBox1.Text = "";
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(13, 159);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(121, 33);
            this.button2.TabIndex = 2;
            this.button2.Text = "读取文件";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 212);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 3;
            this.label1.Text = "未读取文件";
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(12, 257);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(122, 31);
            this.button3.TabIndex = 4;
            this.button3.Text = "文件复制";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(779, 453);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        #endregion
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button3;
    }
}

有好的建议,请在下方输入你的评论。

C#(四十六)之基于流的文件操作(FileStream),c#,服务器,开发语言文章来源地址https://www.toymoban.com/news/detail-526588.html

到了这里,关于C#(四十六)之基于流的文件操作(FileStream)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C# IO FileStream流(一)使用整理

    一、C# IO 文件流,常用操作整理 来自其他开发者的整理: 文件操作常用相关类 1)Directory //操作目录(文件夹),静态类。 2)Path//静态类,对文件或目录的路径进行操作(很方便)【字符串】 3)File //操作文件,静态类,对文件整体操作。拷贝、删除、剪切等。 4)DriveInfo //获取磁

    2024年02月15日
    浏览(28)
  • 四十六、B+树

    这一次我们来介绍B+树。 一个m阶的B树具有如下几个特征: 1.根结点至少有两个子女。 2.每个中间节点都包含k-1个元素和k个孩子,其中 m/2 = k = m 3.每一个叶子节点都包含k-1个元素,其中 m/2 = k = m 4.所有的叶子结点都位于同一层。 5.每个节点中的元素从小到大排列,节点当中

    2024年02月09日
    浏览(30)
  • OpenCV(四十六):特征点匹配

    1.特征点匹配的定义         特征点匹配是一种在两幅图像中寻找相互对应的特征点,并建立它们之间的对应关系的过程。 具体而言,首先通过特征检测算法在两幅图像中寻找相互对应的特征点,然后,对于每个特征点,通过描述子提取算法计算其描述子,最后,使用匹配算

    2024年02月07日
    浏览(50)
  • 算法训练第四十六天

    139. 单词拆分 - 力扣(LeetCode) 总结:自己一开始想的利用回溯来解决但是也考虑到可能会超时,从动归角度入手,自己没有弄清楚dp数组的含义而导致没有正确解决问题,此题的dp数组是当字符串的子串长度为i时,dp[i]表示能否用给定字典中的串表示出来,此题是一个排列的

    2024年02月11日
    浏览(33)
  • 第四十六章 Unity 布局(上)

    学习了UI元素的使用,并不能构建出一个完整的UI界面,我们需要使用一些方法将这些UI元素按照“设计稿”的效果,将其摆放到对应的位置上。如何摆放这些UI元素,就是我们需要讲的“布局”,当然这需要借助一些布局组件来完成。我们知道在画布Canvas下的每个UI元素都会自

    2024年02月03日
    浏览(24)
  • 第四十六章 动态规划——状态机模型

    其实状态机DP只是听起来高级,其实我们之前做的所有关于DP的题几乎都算是状态机,为什么呢? 大家继续向下看: DP解决的是多决策的问题,那么我们可以把01背包问题画成下面的图: 按照正常的逻辑,我们一般都是从第一个物品开始看,决定选或者不选,然后再去看第二

    2024年02月16日
    浏览(35)
  • 第四十六节 Java 8 Stream

    Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。 Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。 Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。

    2024年04月23日
    浏览(24)
  • 学习JAVA打卡第四十六天

    Date和Calendar类 Date类 ⑴使用无参数构造方法 使用Date 类的无参数构造方法创建的对象可以获取本机的当前日期和时间,例如: Date nowtime =new Date(); ⑵使用带参数的构造方法 计算机系统将其自身的时间的设“公元”设置在1970年1月1日零时可(格林威治时间),可以根据这个

    2024年02月11日
    浏览(37)
  • 四十六、docker-compose部署

    一个项目肯定包含多个容器,每个容器都手动单独部署肯定费时费力。docker-compose可以通过脚本来批量构建镜像和启动容器,快速的部署项目。 使用docker-compose部署主要是编写docker-compose.yml脚本。 不论是Dockerfile还是docker-compose.yml脚本的编写都依赖上下文,所以需要明确部署文

    2023年04月19日
    浏览(30)
  • 【微信小程序】-- 案例 - 自定义 tabBar(四十六)

    💌 所属专栏:【微信小程序开发教程】 😀 作  者:我是夜阑的狗🐶 🚀 个人简介:一个正在努力学技术的CV工程师,专注基础和实战分享 ,欢迎咨询! 💖 欢迎大家:这里是CSDN,我总结知识的地方,喜欢的话请三连,有问题请私信 😘 😘 😘   大家好,又见面了,

    2024年02月03日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包