C#保存文件

        /// <summary>
        /// 写字节数组到文件
        /// </summary>
        /// <param name="buff"></param>
        /// <param name="filePath"></param>
        public static void WriteBuffToFile(byte[] buff, string filePath)
        {
            WriteBuffToFile(buff, 0, buff.Length, filePath);
        }
        /// <summary>
        /// 写字节数组到文件
        /// </summary>
        /// <param name="buff"></param>
        /// <param name="offset">开始位置</param>
        /// <param name="len"></param>
        /// <param name="filePath"></param>
        public static void WriteBuffToFile(byte[] buff, int offset, int len, string filePath)
        {
            string directoryName = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            FileStream output = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            BinaryWriter writer = new BinaryWriter(output);
            writer.Write(buff, offset, len);
            writer.Flush();
            writer.Close();
            output.Close();
        }

调用: 

using (MemoryStream ms = new MemoryStream())
{
    hssfworkbook.Write(ms);
    //设置excel保存到服务器的路径   
    var tpath = "/" + Guid.NewGuid().ToString() + ".xls";
    var filePath = filePathBase + tpath;
    //保存excel到指定路径         
    WriteBuffToFile(ms.ToArray(), filePath);
    context.Response.Write(JsonConvert.SerializeObject(new { filePath = "/temp/" + tpath, flag = flag, pageIndex = pageIndex }));
}

猜你喜欢

转载自blog.csdn.net/qq_32109957/article/details/82978267