示例代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 使用FileStream读数据
            FileStream fsRead = new FileStream(@"E:\net-code\test.txt", FileMode.OpenOrCreate);
            byte[] buffer = new byte[1024 * 1024 * 5];
            int r = fsRead.Read(buffer, 0, buffer.Length);
            string s = Encoding.Default.GetString(buffer, 0, r);
            fsRead.Close();
            fsRead.Dispose();
            Console.WriteLine(s);
            Console.ReadKey();

            // 使用FileStream写数据
            using (FileStream fsWrite = new FileStream(@"E:\net-code\test.txt", FileMode.OpenOrCreate))
            {
                string str = "hello 20240806";
                byte[] buff = Encoding.Default.GetBytes(str);
                fsWrite.Write(buff, 0, buff.Length);
            }
            Console.WriteLine("写入success");
            Console.ReadKey();
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string source = @"E:\net-code\abc.avi";
            string target = @"E:\net-code\ConsoleApp1\abc.avi";
            CopyFile(source, target);
        }

        public static void CopyFile(string source, string target)
        {
            // 1. 创建一个负责读取的流
            using (FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read))
            {
                // 2. 创建一个负责写入的流
                using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate))
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    while (true)
                    {
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        if (r == 0)
                        {
                            break;
                        }
                        fsWrite.Write(buffer, 0, r);
                    }
                }
            }
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

 

直接结果

【C#】FileStream读取、写入文件和复制多媒体文件_c#