文件存储格式转换的运用

/********************************************************************************
     File:                
            TransfileToData.cs                        
     Description:
            文件转和二进制转换
     Author:         
            liqiuping
     Finish DateTime:
   2010-05-13 14:54:30
     History:
*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Web;
using System.IO;

namespace FrameWork.Comm
{
    public class TransfileToData
    {
        //根据文件名(完全路径)
        public static byte[] SetImageToByteArray(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open);
            int streamLength = (int)fs.Length;
            byte[] image = new byte[streamLength];
            fs.Read(image, 0, streamLength);
            fs.Close();
            return image;
        }

        //另外,在ASP.NET中通过FileUpload控件得到的图像文件可以通过以下方法
        public static byte[] SetImageToByteArray(FileUpload FileUpload1)
        {
            Stream stream = FileUpload1.PostedFile.InputStream;
            byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
            stream.Read(photo, 0, FileUpload1.PostedFile.ContentLength);
            stream.Close();
            return photo;
        }

        //根据ASP.NET中的HttpFileCollection 返回的数组遍历HttpPostedFile的方法
        public static byte[] SetImageToByteArray(HttpPostedFile httpfile) {
            Stream stream = httpfile.InputStream;
            byte[] photo = new byte[httpfile.ContentLength];
            stream.Read(photo, 0, httpfile.ContentLength);
            stream.Close();
            return photo;
        }

        //要使用SqlDataReader要加载using System.Data.SqlClient命名空间
        //将数据库中的Image类型转换成byte[]
        public static byte[] SetImage(SqlDataReader reader, string Fleid)
        {
            return (byte[])reader[Fleid];//Image为数据库中存放Image类型字段
        }

        //将byte[]转换成Image图像类型
        //加载以下命名空间using System.Drawing;/using System.IO;
        public static System.Drawing.Image SetByteToImage(byte[] mybyte)
        {
            System.Drawing.Image image;
            MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
            image = System.Drawing.Image.FromStream(mymemorystream);
            return image;
        }

        /// <summary>
        /// 将byte[]转换成指定目录文件
        /// </summary>
        /// <param name="path">存放文件的路径</param>
        /// <param name="bydata">byte流</param>
        public static void ByteArrayToFile(string path,byte[] bydata) {
            //if (File.Exists(path)) {
            //    KillProcess(path);
            //    File.Delete(path); }

            FileStream xlsFile = new FileStream(path, FileMode.OpenOrCreate);
            char[] cpara = Encoding.Default.GetChars(bydata);

            // Move file pointer to beginning of file
            xlsFile.Seek(0, SeekOrigin.Begin);
            xlsFile.Write(bydata, 0, bydata.Length);    //将字节数据写入文件               
            xlsFile.Close();
        }

        /// <summary>
        /// 保存附件至本地
        /// </summary>
        /// <param name="context">页面对象</param>
        /// <param name="contentType">文件类型:例 application/zip</param>
        /// <param name="fileName">文件名称:例 20100510.zip</param>
        /// <param name="content">byte[]值</param>
        public static void ProcessRequest(HttpContext context, string contentType,string fileName,byte[] content)
        {
            context.Response.Buffer = true;
            context.Response.Clear();
            context.Response.ContentType = contentType;
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8) + "");
            context.Response.BinaryWrite((byte[])content);
            context.Response.Flush();
            context.Response.End();
        }
        /// <summary>
        /// 转换位字节数
        /// </summary>
        /// <param name="strbyte"></param>
        public static string ByteToSize(int intbyte) {
            string Size = float.Parse(Convert.ToString(intbyte / 1024.00)) > 1024 ?
                float.Parse(Convert.ToString(intbyte / 1024.00 / 1024.00)).ToString("0.00") + "KB" :
                float.Parse(Convert.ToString(intbyte / 1024.00)).ToString("0.00") + "MB";
            return Size;
        }


        #region 杀死进程
        /// <summary>
        /// 进程名
        /// </summary>
        /// <param name="processName"></param>
        private static void KillProcess(string processName)
        {
            //获得进程对象,以用来操作   
            Process myproc = new Process();
            //得到所有打开的进程    
            try
            {
                //获得需要杀死的进程名   
                foreach (Process thisproc in Process.GetProcessesByName(processName))
                {
                    //立即杀死进程                  
                    thisproc.Kill();
                }
            }
            catch (Exception Exc)
            {
                throw new Exception("", Exc);
            }
        }
        #endregion
 
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">要删除文件的路径</param>
        public static void DeleteFile(string filePath)
        {
            System.IO.DirectoryInfo directory = new DirectoryInfo(filePath);

            FileInfo[] files = directory.GetFiles();

            if (files.Length == 0)
                return;

            for (int i = 0; i < files.Length; i++)
            {
                //if (files[i].Extension != ".xls")
                //    continue;
                if (files[i].Name.Length != 49) continue;

                string[] strDate = files[i].Name.Split('-');

                DateTime oldDate = new DateTime(Convert.ToInt32(strDate[0].Substring(0, 4)),
                    Convert.ToInt32(strDate[0].Substring(4, 2)), Convert.ToInt32(strDate[0].Substring(6, 2)));

                if (oldDate.CompareTo(DateTime.Today) < 0)
                {
                    try
                    {
                        files[i].Delete();
                    }
                    catch
                    { }
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值