(精华)2020年6月27日 C#类库 Stream(扩展方法)

using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Core.Util
{
     
    public static partial class Extention
    {
     
        /// 
        /// 将流读为字符串
        /// 注:默认使用UTF-8编码
        /// 
        /// 
        /// 指定编码
        /// 
        public static async Task<string> ReadToStringAsync(this Stream stream, Encoding encoding = null)
        {
     
            if (encoding == null)
                encoding = Encoding.UTF8;

            if (stream.CanSeek)
            {
     
                stream.Seek(0, SeekOrigin.Begin);
            }

            string resStr = string.Empty;
            resStr = await new StreamReader(stream, encoding).ReadToEndAsync();

            if (stream.CanSeek)
            {
     
                stream.Seek(0, SeekOrigin.Begin);
            }

            return resStr;
        }
    }
}

你可能感兴趣的:(#,C#类库/扩展方法,asp.net,c#,后端)