注册 登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

我只是一个人

我爱一个人

 
 
 

日志

 
 

文件操作  

2011-05-17 12:38:42|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text.RegularExpressions;
using System.Net;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

/// <summary>
///Common 的摘要说明
/// </summary>
public class Common
{
 public Common()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //
 }

    protected static void AddTextWatermark(float position, FileInfo fileInfo)
    {

        Random myRd = new Random();
        string Copyright = "Copyright ? 2010  - 沸腾畜牧招商";

        System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(fileInfo.FullName);
        int phWidth = imgPhoto.Width;
        int phHeight = imgPhoto.Height;
        Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(72, 72);//字体的大小
        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
        grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, phWidth, phHeight), 0, 0, phWidth, phHeight, GraphicsUnit.Pixel);
        int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };
        Font crFont = null;
        SizeF crSize = new SizeF();
        for (int i = 0; i < 7; i++)
        {
            crFont = new Font("arial", sizes[i], FontStyle.Bold);

            crSize = grPhoto.MeasureString(Copyright, crFont);


            if ((ushort)crSize.Width < (ushort)phWidth)
                break;
        }
        // int yPixlesFromBottom = (int)(phHeight * 0.07);//距离底部的位置
        int yPixlesFromBottom = 15;
        float yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));

        float xCenterOfImg = ((phWidth / 2) - position);

        StringFormat StrFormat = new StringFormat();
        StrFormat.Alignment = StringAlignment.Near;
        SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

        grPhoto.DrawString(Copyright, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat);

        SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
        grPhoto.DrawString(Copyright, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat);
        //imgPhoto = bmPhoto;
        grPhoto.Dispose();
        imgPhoto.Dispose();
        fileInfo.Delete();
        bmPhoto.Save(fileInfo.FullName);
    }

 public static FileInfo UploadSmallProcinfo(FileUpload fu, string file)
    {
        Random myRd = new Random();

        string prefix = System.IO.Path.GetExtension(fu.FileName).ToLower();
        string fileName = "";
        if (prefix.Equals(".jpg") || prefix.Equals(".gif") || prefix.Equals(".jpeg"))
        {
            string strFileName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + myRd.Next(1000) + prefix;
            // string name = System.Web.HttpContext.Current.Server.MapPath(file + strFileName);
            FileInfo imageinfo = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(file + strFileName));
            //fileName = file + strFileName;
            fu.SaveAs(imageinfo.FullName);
            AddTextWatermark(120, imageinfo);


            //fu.SaveAs(name);
            return imageinfo;
        }
        else
        {
            return null;
        }
    }

 public static FileInfo UploadBigProcinfo(FileUpload fu, string file)
 {
     Random myRd = new Random();

     string prefix = System.IO.Path.GetExtension(fu.FileName).ToLower();
     string fileName = "";
     if (prefix.Equals(".jpg") || prefix.Equals(".gif") || prefix.Equals(".jpeg"))
     {
         string strFileName = DateTime.Now.ToString().Replace("-", ""   ).Replace(":", "").Replace(" ", "") + myRd.Next(1000) + prefix;
         // string name = System.Web.HttpContext.Current.Server.MapPath(file + strFileName);
         FileInfo imageinfo = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(file + strFileName));
         //fileName = file + strFileName;
         fu.SaveAs(imageinfo.FullName);
         AddTextWatermark(0, imageinfo);


         //fu.SaveAs(name);
         return imageinfo;
     }
     else
     {
         return null;
     }
 }
    public static string UploadInfo(FileUpload fu, string file)
    {
        Random myRd = new Random();

        string prefix = System.IO.Path.GetExtension(fu.FileName).ToLower();
        string fileName = "";
        if (prefix.Equals(".jpg") || prefix.Equals(".gif") || prefix.Equals(".jpeg"))
        {
            string strFileName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + myRd.Next(1000) + prefix;
            string name = System.Web.HttpContext.Current.Server.MapPath(file + strFileName);
            fileName = file + strFileName;
            fu.SaveAs(name);
            return fileName;
        }
        else
            return null;
    }
    /// <summary>
    /// 获取文本编辑器的数据,并自动上传远程图片
    /// </summary>
    /// <param name="uc">文本编辑器数据</param>
    /// <returns></returns>
    public string GetText(string str)
    {
        string mycontext = Regex.Replace(str, @"src[^>]*[^/].(?:jpg|bmp|gif|png|jpeg|JPG|BMP|GIF|JPEG)(?:\""|\')", new MatchEvaluator(SaveYuanFile));

        return mycontext;
    }

    private string SaveYuanFile(Match m)
    {
        string imgurl = "";
        string matchstr = m.Value;//str[i].ToString();
        string tempimgurl = "";
        tempimgurl = matchstr.Substring(5);
        tempimgurl = tempimgurl.Substring(0, tempimgurl.IndexOf("\""));

        Regex re = new Regex(@"^http://*");
        if (re.Match(tempimgurl).Success)
        {
            matchstr = matchstr.Substring(5);
            matchstr = matchstr.Substring(0, matchstr.IndexOf("\""));

            //Response.Write(matchstr + "<br>");

            //远程文件保存路径
            string Folders = ConfigurationManager.AppSettings["yuanimg"].ToString();
            string fullname = matchstr;

            string huozui = fullname.Substring(fullname.LastIndexOf("."));
            string filename = Common.GetFileName();
            string path = Folders + filename + huozui;
            //Folders+fullname.Substring(fullname.LastIndexOf("\\") + 1);

            if (System.IO.File.Exists(System.Web.HttpContext.Current.Request.MapPath(path)))
                System.IO.File.Delete(System.Web.HttpContext.Current.Request.MapPath(path));
            GetHttpFile(matchstr, System.Web.HttpContext.Current.Request.MapPath(path));
            imgurl = "src=\"" + path.Replace("~/", "") + "\"";
        }
        else
        {
            imgurl = matchstr;
        }


        return imgurl;
    }
    string sException = null;
    private bool GetHttpFile(string sUrl, string sSavePath)
    {
        bool bRslt = false;
        WebResponse oWebRps = null;
        WebRequest oWebRqst = WebRequest.Create(sUrl);
        oWebRqst.Timeout = 100000;
        try
        {
            oWebRps = oWebRqst.GetResponse();
        }
        catch (WebException e)
        {
            sException = e.Message.ToString();
        }
        catch (Exception e)
        {
            sException = e.ToString();
        }
        finally
        {
            if (oWebRps != null)
            {
                BinaryReader oBnyRd = new BinaryReader(oWebRps.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
                int iLen = Convert.ToInt32(oWebRps.ContentLength);
                FileStream oFileStream;
                try
                {
                    if (File.Exists(System.Web.HttpContext.Current.Request.MapPath("RecievedData.tmp")))
                    {
                        oFileStream = File.OpenWrite(sSavePath);
                    }
                    else
                    {
                        oFileStream = File.Create(sSavePath);
                    }
                    oFileStream.SetLength((Int64)iLen);
                    oFileStream.Write(oBnyRd.ReadBytes(iLen), 0, iLen);
                    oFileStream.Close();
                }
                catch (Exception ex)
                {
                    //bRslt= false;
                }
                finally
                {
                    oBnyRd.Close();
                    oWebRps.Close();

                }
                bRslt = true;

            }
        }
        return bRslt;

    }
    /// <summary>
    /// 文件上传
    /// </summary>
    /// <param name="fileupload">文件上传实例</param>
    /// <returns>保存的文件名称</returns>
    public static string UpLoadFile(FileUpload fileupload, string Folders)
    {
        //string Folders = "~/admin/eWebEditor/UpLoadFile/";
        string fullname = fileupload.PostedFile.FileName;
        if ((fullname == null) || (fullname.Equals("")))
            return "";
        string huozui = fullname.Substring(fullname.LastIndexOf("."));
        string filename = GetFileName();
        string p1 = Folders + filename + huozui;
        //Folders + fullname.Substring(fullname.LastIndexOf("\\") + 1);
        string path = System.Web.HttpContext.Current.Server.MapPath(p1);

        if (System.IO.File.Exists(path))
            System.IO.File.Delete(path);
        fileupload.PostedFile.SaveAs(path);
        return p1;
    }
    /// <summary>
    /// 上传文档
    /// </summary>
    /// <param name="fu"></param>
    /// <param name="file"></param>
    /// <param name="strname"></param>
    /// <returns></returns>
    public static string UploadText(FileUpload fu, string file, string strname)
    {
        Random myRd = new Random();

        string prefix = System.IO.Path.GetExtension(fu.FileName).ToLower();
        string fileName = "";
        if (prefix.Equals(".doc") || prefix.Equals(".pdf") || prefix.Equals(".excel") || prefix.Equals(".rar") || prefix.Equals(".txt"))
        {
            string name = System.Web.HttpContext.Current.Server.MapPath(file + strname);
            fileName = file + strname;
            fu.SaveAs(name);
            return fileName;
        }
        else
            return null;
    }
    public static string GetFileName()
    {
        System.Threading.Thread.Sleep(1000);
        string str1 = System.DateTime.Now.Year.ToString() + "-";

        if ((System.DateTime.Now.Month).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Month.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Month.ToString() + "-";
        }

        if ((System.DateTime.Now.Day).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Day.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Day.ToString() + "-";
        }

        if ((System.DateTime.Now.Hour).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Hour.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Hour.ToString() + "-";
        }

        if ((System.DateTime.Now.Minute).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Minute.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Minute.ToString() + "-";
        }

        if ((System.DateTime.Now.Second).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Second.ToString();
        }
        else
        {
            str1 += System.DateTime.Now.Second.ToString();
        }

        return str1;
    }
    /// <summary>
    /// 是否审核
    /// </summary>
    /// <param name="check"></param>
    /// <returns></returns>
    public static string GetCheck(string check)
    {
        //是否审核(0,未审核1,已审核)
        string str = "";
        switch (check)
        {
            case "0":
                str = "<font color=red>未审核</font>";
                break;
            case "1":
                str = "已审核";
                break;
        }
        return str;
    }
    /// <summary>
    /// 格式化时间
    /// </summary>
    /// <param name="time"></param>
    /// <returns></returns>
    public static string GetFormatTime(string time)
    {
        DateTime dt = Convert.ToDateTime(time);
        return dt.ToShortDateString();
    }
   
    public static string NoHTML(string Htmlstring) //去除HTML标记
    {
        //删除脚本
        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除HTML
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

        Htmlstring.Replace("<", "");
        Htmlstring.Replace(">", "");
        Htmlstring.Replace("\r\n", "");
        Htmlstring = Htmlstring.Replace("[\\s]{2,{", " ");
        Htmlstring = Htmlstring.Replace("( <[b|B][r|R]/*>)+|( <[p|P](.|\\n)*?>)", "\n"); // <br>
        Htmlstring = Htmlstring.Replace("(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //&nbsp;
        Htmlstring = Htmlstring.Replace(" <(.|\\n)*?>", string.Empty); //any other tags
        Htmlstring = Htmlstring.Replace("\r\n", "<br>");
        Htmlstring = Htmlstring.Replace("=", "");
        Htmlstring = Htmlstring.Replace("%", "");
        Htmlstring = Htmlstring.Replace("'", "");
        Htmlstring = Htmlstring.Replace("select ", "");
        Htmlstring = Htmlstring.Replace("insert ", "");
        Htmlstring = Htmlstring.Replace("delete ", "");
        Htmlstring = Htmlstring.Replace(" or", "");
        Htmlstring = Htmlstring.Replace("exec ", "");
        Htmlstring = Htmlstring.Replace("--", "");
        Htmlstring = Htmlstring.Replace(" and", "");
        Htmlstring = Htmlstring.Replace(" AND", "");
        Htmlstring = Htmlstring.Replace(" And", "");
        Htmlstring = Htmlstring.Replace(" AnD", "");
        Htmlstring = Htmlstring.Replace(" ANd", "");
        Htmlstring = Htmlstring.Replace(" aND", "");
        Htmlstring = Htmlstring.Replace(" aNd", "");
        Htmlstring = Htmlstring.Replace(" anD", "");
        Htmlstring = Htmlstring.Replace("where ", "");
        Htmlstring = Htmlstring.Replace("update ", "");
        Htmlstring = Htmlstring.Replace("script", "");
        Htmlstring = Htmlstring.Replace("iframe", "");
        Htmlstring = Htmlstring.Replace("master", "");
        Htmlstring = Htmlstring.Replace("&nbsp;", "");
        Htmlstring = Htmlstring.Replace("exec ", "");
        Htmlstring = Htmlstring.Replace("exists", "");
        Htmlstring = Htmlstring.Replace("drop", "");
        Htmlstring = Htmlstring.Replace("996008E", "");
        Htmlstring = Htmlstring.Replace("ar(124)", "");
        Htmlstring = Htmlstring.Replace("1and", "");
        Htmlstring = Htmlstring.Replace("0and", "");
        Htmlstring = Htmlstring.Replace("chr(", "");
        Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

        return Htmlstring;
    }

    /// <summary>
    /// 截取字符串
    /// </summary>
    /// <param name="name"></param>
    /// <param name="num"></param>
    /// <returns></returns>
    public static string GetSubString(string name, int num)
    {
        string a = name;
        if (a.Length > num)
        {
            a = name.Substring(0, num) + "...";
        }
        return a;
    }
    public static string GetSubStrings(string name, int num)
    {
        string a = name;
        if (a.Length > num)
        {
            a = name.Substring(0, num);
        }
        return a;
    }
    public static bool IsInteger(object obj)
    {
        //为指定的正则表达式初始化并编译 Regex 类的实例
        System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^-?(\d*)$");
        //在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式匹配项
        System.Text.RegularExpressions.Match mc = rg.Match(obj.ToString());
        //指示匹配是否成功
        return (mc.Success);
    }

    //格式化图片路径
    public static string formatPics(string str)
    {
        return str.Replace("~", "");
    }
    //过滤字符串
    public static string Htmlstr(string myString) //去除HTML标记
    {
        myString = myString.Replace("\r\n", "<br>");
        myString = myString.Replace(" ", "&nbsp;");
        return myString;
    }

    public static string HtmlEdit(string myString)
    {
        myString = myString.Replace("<br>", "\r\n");
        myString = myString.Replace("&nbsp;", " ");
        return myString;
    }
    /// <summary>
    /// 创建文件夹
    /// </summary>
    /// <param name="directoryPath"></param>
    public static void CreatDirectory(string directoryPath)
    {
        try
        {
            DirectoryInfo dirInfo;
            string new_path = System.Web.HttpContext.Current.Server.MapPath(directoryPath);
            dirInfo = new DirectoryInfo(new_path);
            if (!dirInfo.Exists)
            {
                System.IO.Directory.CreateDirectory(new_path);
            }
        }
        catch (System.Exception E)
        {
            throw;
        }
    }
}

  评论这张
 
阅读(76)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018