欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# read file to bytes,File.ReadAllFiles,File.Open(),BinaryReader

程序员文章站 2022-05-03 12:42:20
using System; using System.Text; using System.IO; namespace ConsoleApplication15 { class Program { static void Main(string[] args) { string fileName =... ......
using system;
using system.text;
using system.io;

namespace consoleapplication15
{
    class program
    {
        static void main(string[] args)
        {
            string filename = @"..\..\images\lj.jpg";
            filestreamreadtobytes(filename);
            readfiletobinarybytes(filename);
            filereadallbytesdemo(filename);
            console.readline();
        }

        static void filestreamreadtobytes(string filename)
        {
            if(!file.exists(filename))
            {
                return;
            }

            byte[] bytesarr = null;
            using (filestream fs = new filestream(filename, filemode.open))
            {
                bytesarr = new byte[fs.length];
                fs.write(bytesarr, 0, bytesarr.length);
                console.writeline(bytesarr.length);
            }
        }

        static void filereadallbytesdemo(string filename)
        {
            byte[] readbytes = system.io.file.readallbytes(filename);
            console.writeline(readbytes.length);
        }

        static void readfiletobinarybytes(string filename)
        {
            if (!file.exists(filename))
            {
                return;
            }

            byte[] bytesarr = null;
            using (filestream fs = new filestream(filename, filemode.open))
            {
                using (binaryreader binreader = new binaryreader(fs,encoding.utf8))
                {
                    bytesarr = binreader.readbytes((int)fs.length);
                    console.writeline(bytesarr.length);
                }                    
            }
        }
    }    
}