zoukankan      html  css  js  c++  java
  • C# IOUtility IO相关

    代码
    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Reflection;
    using System.Text;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization.Formatters.Soap;
    using Rocky.Stored;

    namespace Rocky.Utils
    {
    public static class IOUtility
    {
    #region Fields
    public static readonly LIFOPool<MemoryStream> MemoryPool;
    private static BinaryFormatter innerBinaryFormatter;
    private static SoapFormatter innerSoapFormatter;
    #endregion

    #region Properties
    public static BinaryFormatter InnerBinaryFormatter
    {
    get
    {
    if (innerBinaryFormatter == null)
    {
    innerBinaryFormatter
    = new BinaryFormatter();
    }
    return innerBinaryFormatter;
    }
    }
    public static SoapFormatter InnerSoapFormatter
    {
    get
    {
    if (innerSoapFormatter == null)
    {
    innerSoapFormatter
    = new SoapFormatter();
    }
    return innerSoapFormatter;
    }
    }
    #endregion

    #region Constructor
    static IOUtility()
    {
    Freer.Instance.Register(MemoryPool
    = new LIFOPool<MemoryStream>(
    ()
    => new MemoryStream(0x800),
    stream
    =>
    {
    stream.Position
    = 0L;
    stream.SetLength(
    0L);
    }));
    }
    #endregion

    #region Directory
    public static void CreateDirectoryIfNotExists(string path)
    {
    path
    = Path.GetDirectoryName(AppRuntime.MapPath(path));
    if (!Directory.Exists(path))
    {
    Directory.CreateDirectory(path);
    }
    }
    #endregion

    #region File
    public static string ReadFile(string path)
    {
    path
    = AppRuntime.MapPath(path);
    using (StreamReader reader = new StreamReader(path, Encoding.Default))
    {
    return reader.ReadToEnd();
    }
    }
    public static void WriteFile(string path, string content)
    {
    WriteFile(path, content,
    false);
    }
    public static void WriteFile(string path, string content, bool append)
    {
    path
    = AppRuntime.MapPath(path);
    using (StreamWriter writer = new StreamWriter(path, append, Encoding.Default))
    {
    writer.Write(content);
    }
    }

    public static byte[] BinaryReadFile(string path)
    {
    path
    = AppRuntime.MapPath(path);
    using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
    long length = stream.Length;
    if (length > int.MaxValue)
    {
    throw new IOException("FileTooLong2GB");
    }
    using (BinaryReader reader = new BinaryReader(stream, Encoding.Default))
    {
    if (reader.PeekChar() == -1)
    {
    throw new IOException();
    }
    int count = (int)length;
    return reader.ReadBytes(count);
    }
    }
    }
    public static void BinaryWriteFile(string path, byte[] buffer)
    {
    BinaryWriteFile(path, buffer,
    false);
    }
    public static void BinaryWriteFile(string path, byte[] buffer, bool append)
    {
    path
    = AppRuntime.MapPath(path);
    long length = buffer.LongLength;
    if (length > int.MaxValue)
    {
    throw new IOException("FileTooLong2GB");
    }
    int count = (int)length;
    using (FileStream stream = new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write))
    using (BinaryWriter writer = new BinaryWriter(stream, Encoding.Default))
    {
    writer.Write(buffer,
    0, count);
    }
    }

    public static void CreateFileFromResource(bool isCalling, string name, string filePath)
    {
    Assembly dll
    = isCalling ? Assembly.GetCallingAssembly() : Assembly.GetExecutingAssembly();
    CreateFileFromResource(dll.GetManifestResourceStream(name), filePath);
    }
    public static void CreateFileFromResource(string dllPath, string name, string filePath)
    {
    Assembly dll
    = Assembly.LoadFile(dllPath);
    CreateFileFromResource(dll.GetManifestResourceStream(name), filePath);
    }
    internal static void CreateFileFromResource(Stream stream, string filePath)
    {
    using (stream)
    using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
    {
    byte[] buffer = new byte[BufferUtility.FileBufferSize];
    int read;
    while ((read = stream.Read(buffer, 0, buffer.Length)) != 0)
    {
    fileStream.Write(buffer,
    0, read);
    fileStream.Flush();
    }
    }
    }

    public static Encoding GetEncoding(FileStream stream)
    {
    Encoding targetEncoding
    = null;
    if (stream.Length >= 2)
    {
    //保存文件流的前4个字节
    byte byte1 = 0;
    byte byte2 = 0;
    byte byte3 = 0;
    byte byte4 = 0;
    //保存当前Seek位置
    long origPos = stream.Seek(0, SeekOrigin.Begin);
    stream.Seek(
    0, SeekOrigin.Begin);
    byte1
    = Convert.ToByte(stream.ReadByte());
    byte2
    = Convert.ToByte(stream.ReadByte());
    if (stream.Length >= 3)
    {
    byte3
    = Convert.ToByte(stream.ReadByte());
    }
    if (stream.Length >= 4)
    {
    byte4
    = Convert.ToByte(stream.ReadByte());
    }
    //根据文件流的前4个字节判断Encoding
    //Unicode {0xFF, 0xFE};
    //BE-Unicode {0xFE, 0xFF};
    //UTF8 = {0xEF, 0xBB, 0xBF};
    if (byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
    {
    targetEncoding
    = Encoding.BigEndianUnicode;
    }
    if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
    {
    targetEncoding
    = Encoding.Unicode;
    }
    if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
    {
    targetEncoding
    = Encoding.UTF8;
    }
    //恢复Seek位置
    stream.Seek(origPos, SeekOrigin.Begin);
    }
    return targetEncoding;
    }
    #endregion

    #region Bytes
    public static byte[] ToBytes(Stream stream)
    {
    long position = stream.Position;
    MemoryStream memory
    = MemoryPool.Retrieve();
    try
    {
    byte[] buffer = new byte[BufferUtility.DefaultBufferSize];
    int read;
    while ((read = stream.Read(buffer, 0, buffer.Length)) != 0)
    {
    memory.Write(buffer,
    0, read);
    }
    return memory.ToArray();
    }
    finally
    {
    stream.Position
    = position;
    MemoryPool.Store(memory);
    }
    }

    public static byte[] Compress(byte[] data)
    {
    MemoryStream stream
    = MemoryPool.Retrieve();
    try
    {
    using (DeflateStream zipStream = new DeflateStream(stream, CompressionMode.Compress))
    {
    zipStream.Write(data,
    0, data.Length);
    return stream.ToArray();
    }
    }
    finally
    {
    MemoryPool.Store(stream);
    }
    }

    public static byte[] Decompress(byte[] data)
    {
    MemoryStream stream
    = MemoryPool.Retrieve();
    try
    {
    using (DeflateStream zipStream = new DeflateStream(new MemoryStream(data), CompressionMode.Decompress))
    {
    byte[] buffer = new byte[BufferUtility.DefaultBufferSize];
    int read;
    while ((read = zipStream.Read(buffer, 0, buffer.Length)) != 0)
    {
    stream.Write(buffer,
    0, read);
    }
    return stream.ToArray();
    }
    }
    finally
    {
    MemoryPool.Store(stream);
    }
    }
    #endregion

    #region Serialization
    public static byte[] BinarySerialize(object obj)
    {
    return BinarySerialize(obj, false);
    }
    public static byte[] BinarySerialize(object obj, bool compress)
    {
    MemoryStream stream
    = MemoryPool.Retrieve();
    try
    {
    InnerBinaryFormatter.Serialize(stream, obj);
    stream.SetLength(stream.Position);
    return compress ? IOUtility.Compress(stream.ToArray()) : stream.ToArray();
    }
    finally
    {
    MemoryPool.Store(stream);
    }
    }

    public static object BinaryDeserialize(byte[] data)
    {
    return BinaryDeserialize(data, false);
    }
    public static object BinaryDeserialize(byte[] data, bool decompress)
    {
    if (decompress)
    {
    data
    = IOUtility.Decompress(data);
    }
    MemoryStream stream
    = MemoryPool.Retrieve();
    try
    {
    stream.Write(data,
    0, data.Length);
    stream.Position
    = 0L;
    return InnerBinaryFormatter.Deserialize(stream);
    }
    finally
    {
    MemoryPool.Store(stream);
    }
    }

    public static byte[] SoapSerialize(object obj)
    {
    return SoapSerialize(obj, false);
    }
    public static byte[] SoapSerialize(object obj, bool compress)
    {
    MemoryStream stream
    = MemoryPool.Retrieve();
    try
    {
    InnerSoapFormatter.Serialize(stream, obj);
    stream.SetLength(stream.Position);
    return compress ? IOUtility.Compress(stream.ToArray()) : stream.ToArray();
    }
    finally
    {
    MemoryPool.Store(stream);
    }
    }

    public static object SoapDeserialize(byte[] data)
    {
    return SoapDeserialize(data, false);
    }
    public static object SoapDeserialize(byte[] data, bool decompress)
    {
    if (decompress)
    {
    data
    = IOUtility.Decompress(data);
    }
    MemoryStream stream
    = MemoryPool.Retrieve();
    try
    {
    stream.Write(data,
    0, data.Length);
    stream.Position
    = 0L;
    return InnerSoapFormatter.Deserialize(stream);
    }
    finally
    {
    MemoryPool.Store(stream);
    }
    }
    #endregion
    }
    }
  • 相关阅读:
    常用的IDEA快捷键
    异步任务 & 定时任务 & 邮件任务
    Swagger
    路由钩子&异步请求axios
    vue-参数绑定及重定向
    Spring事务的传播机制
    使用mybatis的BaseTypeHandler来给敏感字段进行AES加密
    SpringBoot2.0.3.RELEASE+sharding-jdbc4.1.0+mybatis-plus3.4.1+druid1.1.22 快速搭建分库分表
    使用SpringCloudStream整合RabbitMQ
    获取汉字首字母
  • 原文地址:https://www.cnblogs.com/Googler/p/1752323.html
Copyright © 2011-2022 走看看