当前位置: 编程技术>.net/c#/asp.net
一个C#实现的目录与文件操作类
来源: 互联网 发布时间:2014-08-30
本文导语: 代码如下: 代码示例: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlContro...
代码如下:
代码示例:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
///
/// 文件操作类
///
public static class FileCom
{
//普通文件或图片上传
#region 文件名命名 和 文件类别验证
///
/// 产生随即文件名
///
///
public static int GetRandomFileName()
{
byte[] bytes = new byte[10];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
///
/// 产生随机文件名
///
/// 随机文件名长度
/// 产生随机文件名
private static string GetRandomFileName(int length)
{
string ch = "abcdefghijklmnopqrstuvwxyz0123456789";
string strRandomFileName = string.Empty;
int intLength = ch.Length;
Random rd = new Random();
for (int i = 0; i < length; i++)
{
strRandomFileName += ch[rd.Next(intLength)];
}
return strRandomFileName;
}
///
/// 产生唯一文件名
///
/// 文件夹路径
/// 扩展名
/// 文件名
public static string GetOnlyFileName(string strPath, string strExt)
{
// 若文件夹不存在, 创建文件夹
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(strPath)))
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(strPath));
}
string strTempFileName = string.Empty;
string strTempFullName = string.Empty;
// 循环方式取唯一文件名
while (true)
{
strTempFileName = GetRandomFileName(15);
strTempFullName = strPath + strTempFileName + "." + strExt;
if (!System.IO.File.Exists(strTempFullName))
{
break;
}
}
return strTempFileName + "." + strExt;
}
///
/// 文件名是否图片文件
///
/// 文件名
/// 是否图片文件
public static bool IsImageExt(string filename)
{
if (filename == null || filename == string.Empty)
return false;
//string[] extArray = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
//string[] extArray = {".jpg", ".jpeg"};
string[] extArray = { ".gif", ".jpg", ".jpeg", ".png" };
foreach (string ext in extArray)
{
if (filename.ToLower().EndsWith(ext))
return true;
}
return false;
}
///
/// 文件名是否图片文件或flash文件
///
/// 文件名
/// 是否图片文件
public static bool IsImageOrFlashExt(string filename)
{
if (filename == null || filename == string.Empty)
return false;
string[] extArray = { ".gif", ".jpg", ".jpeg", ".bmp", ".png", ".swf" };
foreach (string ext in extArray)
{
if (filename.ToLower().EndsWith(ext))
return true;
}
return false;
}
#endregion
#region 文件夹或文件创建 删除操作/图片 文件上传类
///
/// .net自带IO方法创建文件夹(注意权限问题)
///
/// 建立文件夹相对路径
/// true:建立成功 false:此文件夹名已存在
public static void IOCreateFolder(string folderpath)
{
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath)))
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(folderpath));
}
}
///
/// 删除一个文件夹下所有文件和文件夹
///
///
public static void DelFolderandFiles(string folderpath)
{
if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath)))
{
System.IO.DirectoryInfo spath = new System.IO.DirectoryInfo(HttpContext.Current.Server.MapPath(folderpath));
foreach (System.IO.DirectoryInfo folder in spath.GetDirectories())
{
folder.Delete();
}
foreach (System.IO.FileInfo file in spath.GetFiles())
{
file.Delete();
}
}
}
///
/// 单个文件夹删除类
///
///
public static void DelFolder(string folderpath)
{
if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath)))
{
System.IO.Directory.Delete(HttpContext.Current.Server.MapPath(folderpath));
}
}
///
/// 单个文件删除类
///
/// 文件相对路径
public static void DelFile(string filePath)
{
if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(filePath)))
{
System.IO.File.Delete(HttpContext.Current.Server.MapPath(filePath));
}
}
///
/// 普通图片上传类
///
/// 图片文件名(可返回)
/// 上传控件名
/// 原始图片地址
/// 图片存放路径
/// 图片限制大小的值
/// true:文件上传成功!false:图片类型错误或大小超过限制大小值
public static bool UpLoadImg(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldpic, string filePath, int size)
{
fileName = file.PostedFile.FileName;
fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf("."));
string type = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (IsImageExt(fileName) && file.PostedFile.ContentLength < size && file.PostedFile.ContentLength > 0)
{
DelFile(filePath + "//" + oldpic);
file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName));
return true;
}
else
{
return false;
}
}
///
/// 普通图片和Flash上传类
///
/// 图片文件名(可返回)
/// 上传控件名
/// 原始图片地址
/// 图片存放路径
/// 图片限制大小的值
/// true:文件上传成功!false:图片类型错误或大小超过限制大小值
public static bool UpLoadImgAndFlash(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldpic, string filePath, int size)
{
fileName = file.PostedFile.FileName;
fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf("."));
string type = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (IsImageOrFlashExt(fileName) && file.PostedFile.ContentLength < size && file.PostedFile.ContentLength > 0)
{
DelFile(filePath + "//" + oldpic);
file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName));
return true;
}
else
{
return false;
}
}
///
/// 检测文件真实类型
///
/// FileUpload控件对象
/// 是否是相关文件类型
/*文件扩展名说明
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*239187 txt,aspx,asp,sql
*208207 xls.doc.ppt
*6063 xml
*6033 htm,html
*4742 js
*8075 xlsx,zip,pptx,mmap,zip
*8297 rar
*01accdb,mdb
*7790 exe,dll
*5666 psd
*255254 rdp
*10056 bt种子
*64101 bat
*/
private static bool IsAllowedExtension(HttpPostedFile hifile)
{
bool ret = false;
System.IO.FileStream fs = new System.IO.FileStream(hifile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
return false;
}
r.Close();
fs.Close();
String[] fileType = { "255216", "7173", "6677", "13780", "8297", "5549", "870", "87111", "8075" };
for (int i = 0; i < fileType.Length; i++)
{
if (fileclass == fileType[i])
{
ret = true;
break;
}
}
return ret;
}
///
/// 任意文件上传类
///
/// 图片文件名(可返回)
/// 上传控件名
/// 原始文件名
/// 存放路径
public static void UpLoadFile(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldfile, string filePath)
{
fileName = file.PostedFile.FileName;
fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf("."));
DelFile(filePath + "//" + oldfile);
file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName));
}
#endregion
//#region 验证上传附件扩展名
/////
///// 验证上传附件扩展名
///// www.
///// FileUpload控件
///// true表示允许,false不允许
//public static bool ValidExt(System.Web.UI.WebControls.FileUpload file)
//{
// BLL.m_config bconfig = new BLL.m_config();
// Model.m_config mconfig = bconfig.GetModel("ValidExt");
// string[] strValiddExt = mconfig.config_value.Split('|');
// bool flag = false;
// foreach (string ext in strValiddExt)
// {
// if (ext == file.FileName.Substring(file.FileName.LastIndexOf('.') + 1).ToLower())
// flag = true;
// }
// return flag;
//}
//#endregion
///
/// 会产生graphics异常的PixelFormat
///
private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare,
PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
PixelFormat.Format8bppIndexed
};
///
/// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中
///
/// 原图片的PixelFormat
///
private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
{
foreach (PixelFormat pf in indexedPixelFormats)
{
if (pf.Equals(imgPixelFormat)) return true;
}
return false;
}
///
/// 添加图片水印
///
/// 企业ID
/// 原始图片路径
public static string AddWaterMark(string filename, int CmyID, string UpLoadPath)
{
string newfilename = string.Empty;
SanRenCMS.BLL.WaterMarkConfig bwmc = new SanRenCMS.BLL.WaterMarkConfig();
SanRenCMS.Model.WaterMarkConfig mwmc = bwmc.GetModel("CmyID=" + CmyID.ToString());
switch (mwmc.WaterMarkType)
{
case 1:
newfilename = LetterWaterMark(filename, mwmc, UpLoadPath);
break;
case 2:
newfilename = PicWaterMark(filename, mwmc, UpLoadPath);
break;
}
return newfilename;
}
///
/// 图片水印上传
///
/// 上传控件
///
///
///
public static string PicWaterMark(string filename, SanRenCMS.Model.WaterMarkConfig mwmc, string UpLoadPicPath)
{
string newfilename = string.Empty;
string MarkHWStr = mwmc.WaterMarkSize; //"50|186";//图片水印的高宽
string[] MyWaterMarkHW = MarkHWStr.Split(new char[] { '|' });
string WaterMarkPath = HttpContext.Current.Server.MapPath(mwmc.WaterMarkPhoto);
string PicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + filename;
newfilename = Guid.NewGuid().ToString() + ".jpg";
string NewPicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + newfilename;
int WaterMarkH = int.Parse(MyWaterMarkHW[0]);
int WaterMarkW = int.Parse(MyWaterMarkHW[1]);
int WaterMarkLight = 80;// 50;//透明度
int WaterMarkPos = mwmc.WaterMarkPosition; //3;//水印图位置(1左上,2右上,3右下,4左下)
System.Drawing.Image image = System.Drawing.Image.FromFile(PicPath);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile(WaterMarkPath);
float[][] numArray2 = new float[5][];
float[] numArray3 = new float[5];
numArray3[0] = 1f; //www.
numArray2[0] = numArray3;
float[] numArray4 = new float[5];
numArray4[1] = 1f;
numArray2[1] = numArray4;
float[] numArray5 = new float[5];
numArray5[2] = 1f;
numArray2[2] = numArray5;
float[] numArray6 = new float[5];
numArray6[3] = ((float)WaterMarkLight) / 100f;
numArray2[3] = numArray6;
float[] numArray7 = new float[5];
numArray7[4] = 1f;
numArray2[4] = numArray7;
float[][] newColorMatrix = numArray2;
ColorMatrix matrix = new ColorMatrix(newColorMatrix);
ImageAttributes imageAttr = new ImageAttributes();
imageAttr.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
Graphics g = null;
if (IsPixelFormatIndexed(image.PixelFormat))
{
Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
g = Graphics.FromImage(image);
}
else
g = Graphics.FromImage(image);
switch (WaterMarkPos)
{
case 1:
g.DrawImage(copyImage, new Rectangle(0, 0, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 2:
g.DrawImage(copyImage, new Rectangle(0, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 3:
g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, 0, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 4:
g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 5:
g.DrawImage(copyImage, new Rectangle((image.Width - WaterMarkW) / 2, (image.Height - WaterMarkH) / 2, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
}
g.Dispose();
image.Save(NewPicPath);
image.Dispose();
if (File.Exists(PicPath))
{
File.Delete(PicPath);
}
return newfilename;
}
///
/// 添加字体水印
///
/// 企业ID
/// 要加水印图片的路径
///
public static string LetterWaterMark(string filename, SanRenCMS.Model.WaterMarkConfig mwmc, string UpLoadPicPath)
{
string newfilename = string.Empty;
Font f;
string PicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + filename;
//HttpContext.Current.Response.Write(filename);
newfilename = Guid.NewGuid().ToString() + ".jpg";
//DateTime.Now.ToString("yyMMddhhmmss") + ".jpg";
string NewPicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + newfilename;
//HttpContext.Current.Response.Write(NewPicPath);
string WaterMarkStr = mwmc.WaterMarkWord;//水印文字
int WaterMarkFontSize = mwmc.WaterMarkWorkSize; //文字大小,单位PX
string WaterMarkFontName = mwmc.WaterMarkFont;// "华文细黑";//字体
string WaterMarkFontColor = mwmc.WaterMarkWordColor;// "009999";//字体颜色
bool WaterMarkIsBold = mwmc.isStrong == 1 ? true : false;//是否加粗
int WaterMarkPos = mwmc.WaterMarkPosition;//水印位置
System.Drawing.Image image = System.Drawing.Image.FromFile(PicPath);
Graphics g = null;
if (IsPixelFormatIndexed(image.PixelFormat))
{
Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
g = Graphics.FromImage(image);
}
else
g = Graphics.FromImage(image);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, 0, 0, image.Width, image.Height);
if (WaterMarkIsBold)
{
f = new Font(WaterMarkFontName, (float)WaterMarkFontSize, FontStyle.Bold);
}
else
{
f = new Font(WaterMarkFontName, (float)WaterMarkFontSize);
}
Brush b = new SolidBrush(ColorTranslator.FromHtml("#" + WaterMarkFontColor));
string addText = WaterMarkStr;
//switch (WaterMarkPos)
//{
// case 1:
// g.DrawString(addText, f, b, (float)0f, (float)0f);
// break;
// case 2:
// g.DrawString(addText, f, b, (float)0f, (float)0f);
// break;
// case 3:
// g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
// break;
// case 4:
// g.DrawImage(copyImage, new Rectangle(0, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
// break;
//}
g.DrawString(addText, f, b, (float)(image.Width / 2), (float)(image.Height / 2));
//g.DrawString(addText,f,b,
g.Dispose();
try
{
//HttpContext.Current.Response.Write(NewPicPath);
image.Save(NewPicPath, ImageFormat.Jpeg);
}
catch (Exception exx)
{
HttpContext.Current.Response.Write(exx.ToString());
}
finally
{
image.Dispose();
}
if (File.Exists(PicPath))
{
File.Delete(PicPath);
}
return newfilename;
}
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
///
/// 文件操作类
///
public static class FileCom
{
//普通文件或图片上传
#region 文件名命名 和 文件类别验证
///
/// 产生随即文件名
///
///
public static int GetRandomFileName()
{
byte[] bytes = new byte[10];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
///
/// 产生随机文件名
///
/// 随机文件名长度
/// 产生随机文件名
private static string GetRandomFileName(int length)
{
string ch = "abcdefghijklmnopqrstuvwxyz0123456789";
string strRandomFileName = string.Empty;
int intLength = ch.Length;
Random rd = new Random();
for (int i = 0; i < length; i++)
{
strRandomFileName += ch[rd.Next(intLength)];
}
return strRandomFileName;
}
///
/// 产生唯一文件名
///
/// 文件夹路径
/// 扩展名
/// 文件名
public static string GetOnlyFileName(string strPath, string strExt)
{
// 若文件夹不存在, 创建文件夹
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(strPath)))
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(strPath));
}
string strTempFileName = string.Empty;
string strTempFullName = string.Empty;
// 循环方式取唯一文件名
while (true)
{
strTempFileName = GetRandomFileName(15);
strTempFullName = strPath + strTempFileName + "." + strExt;
if (!System.IO.File.Exists(strTempFullName))
{
break;
}
}
return strTempFileName + "." + strExt;
}
///
/// 文件名是否图片文件
///
/// 文件名
/// 是否图片文件
public static bool IsImageExt(string filename)
{
if (filename == null || filename == string.Empty)
return false;
//string[] extArray = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
//string[] extArray = {".jpg", ".jpeg"};
string[] extArray = { ".gif", ".jpg", ".jpeg", ".png" };
foreach (string ext in extArray)
{
if (filename.ToLower().EndsWith(ext))
return true;
}
return false;
}
///
/// 文件名是否图片文件或flash文件
///
/// 文件名
/// 是否图片文件
public static bool IsImageOrFlashExt(string filename)
{
if (filename == null || filename == string.Empty)
return false;
string[] extArray = { ".gif", ".jpg", ".jpeg", ".bmp", ".png", ".swf" };
foreach (string ext in extArray)
{
if (filename.ToLower().EndsWith(ext))
return true;
}
return false;
}
#endregion
#region 文件夹或文件创建 删除操作/图片 文件上传类
///
/// .net自带IO方法创建文件夹(注意权限问题)
///
/// 建立文件夹相对路径
/// true:建立成功 false:此文件夹名已存在
public static void IOCreateFolder(string folderpath)
{
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath)))
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(folderpath));
}
}
///
/// 删除一个文件夹下所有文件和文件夹
///
///
public static void DelFolderandFiles(string folderpath)
{
if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath)))
{
System.IO.DirectoryInfo spath = new System.IO.DirectoryInfo(HttpContext.Current.Server.MapPath(folderpath));
foreach (System.IO.DirectoryInfo folder in spath.GetDirectories())
{
folder.Delete();
}
foreach (System.IO.FileInfo file in spath.GetFiles())
{
file.Delete();
}
}
}
///
/// 单个文件夹删除类
///
///
public static void DelFolder(string folderpath)
{
if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath)))
{
System.IO.Directory.Delete(HttpContext.Current.Server.MapPath(folderpath));
}
}
///
/// 单个文件删除类
///
/// 文件相对路径
public static void DelFile(string filePath)
{
if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(filePath)))
{
System.IO.File.Delete(HttpContext.Current.Server.MapPath(filePath));
}
}
///
/// 普通图片上传类
///
/// 图片文件名(可返回)
/// 上传控件名
/// 原始图片地址
/// 图片存放路径
/// 图片限制大小的值
/// true:文件上传成功!false:图片类型错误或大小超过限制大小值
public static bool UpLoadImg(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldpic, string filePath, int size)
{
fileName = file.PostedFile.FileName;
fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf("."));
string type = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (IsImageExt(fileName) && file.PostedFile.ContentLength < size && file.PostedFile.ContentLength > 0)
{
DelFile(filePath + "//" + oldpic);
file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName));
return true;
}
else
{
return false;
}
}
///
/// 普通图片和Flash上传类
///
/// 图片文件名(可返回)
/// 上传控件名
/// 原始图片地址
/// 图片存放路径
/// 图片限制大小的值
/// true:文件上传成功!false:图片类型错误或大小超过限制大小值
public static bool UpLoadImgAndFlash(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldpic, string filePath, int size)
{
fileName = file.PostedFile.FileName;
fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf("."));
string type = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (IsImageOrFlashExt(fileName) && file.PostedFile.ContentLength < size && file.PostedFile.ContentLength > 0)
{
DelFile(filePath + "//" + oldpic);
file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName));
return true;
}
else
{
return false;
}
}
///
/// 检测文件真实类型
///
/// FileUpload控件对象
/// 是否是相关文件类型
/*文件扩展名说明
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*239187 txt,aspx,asp,sql
*208207 xls.doc.ppt
*6063 xml
*6033 htm,html
*4742 js
*8075 xlsx,zip,pptx,mmap,zip
*8297 rar
*01accdb,mdb
*7790 exe,dll
*5666 psd
*255254 rdp
*10056 bt种子
*64101 bat
*/
private static bool IsAllowedExtension(HttpPostedFile hifile)
{
bool ret = false;
System.IO.FileStream fs = new System.IO.FileStream(hifile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
return false;
}
r.Close();
fs.Close();
String[] fileType = { "255216", "7173", "6677", "13780", "8297", "5549", "870", "87111", "8075" };
for (int i = 0; i < fileType.Length; i++)
{
if (fileclass == fileType[i])
{
ret = true;
break;
}
}
return ret;
}
///
/// 任意文件上传类
///
/// 图片文件名(可返回)
/// 上传控件名
/// 原始文件名
/// 存放路径
public static void UpLoadFile(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldfile, string filePath)
{
fileName = file.PostedFile.FileName;
fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf("."));
DelFile(filePath + "//" + oldfile);
file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName));
}
#endregion
//#region 验证上传附件扩展名
/////
///// 验证上传附件扩展名
///// www.
///// FileUpload控件
///// true表示允许,false不允许
//public static bool ValidExt(System.Web.UI.WebControls.FileUpload file)
//{
// BLL.m_config bconfig = new BLL.m_config();
// Model.m_config mconfig = bconfig.GetModel("ValidExt");
// string[] strValiddExt = mconfig.config_value.Split('|');
// bool flag = false;
// foreach (string ext in strValiddExt)
// {
// if (ext == file.FileName.Substring(file.FileName.LastIndexOf('.') + 1).ToLower())
// flag = true;
// }
// return flag;
//}
//#endregion
///
/// 会产生graphics异常的PixelFormat
///
private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare,
PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
PixelFormat.Format8bppIndexed
};
///
/// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中
///
/// 原图片的PixelFormat
///
private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
{
foreach (PixelFormat pf in indexedPixelFormats)
{
if (pf.Equals(imgPixelFormat)) return true;
}
return false;
}
///
/// 添加图片水印
///
/// 企业ID
/// 原始图片路径
public static string AddWaterMark(string filename, int CmyID, string UpLoadPath)
{
string newfilename = string.Empty;
SanRenCMS.BLL.WaterMarkConfig bwmc = new SanRenCMS.BLL.WaterMarkConfig();
SanRenCMS.Model.WaterMarkConfig mwmc = bwmc.GetModel("CmyID=" + CmyID.ToString());
switch (mwmc.WaterMarkType)
{
case 1:
newfilename = LetterWaterMark(filename, mwmc, UpLoadPath);
break;
case 2:
newfilename = PicWaterMark(filename, mwmc, UpLoadPath);
break;
}
return newfilename;
}
///
/// 图片水印上传
///
/// 上传控件
///
///
///
public static string PicWaterMark(string filename, SanRenCMS.Model.WaterMarkConfig mwmc, string UpLoadPicPath)
{
string newfilename = string.Empty;
string MarkHWStr = mwmc.WaterMarkSize; //"50|186";//图片水印的高宽
string[] MyWaterMarkHW = MarkHWStr.Split(new char[] { '|' });
string WaterMarkPath = HttpContext.Current.Server.MapPath(mwmc.WaterMarkPhoto);
string PicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + filename;
newfilename = Guid.NewGuid().ToString() + ".jpg";
string NewPicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + newfilename;
int WaterMarkH = int.Parse(MyWaterMarkHW[0]);
int WaterMarkW = int.Parse(MyWaterMarkHW[1]);
int WaterMarkLight = 80;// 50;//透明度
int WaterMarkPos = mwmc.WaterMarkPosition; //3;//水印图位置(1左上,2右上,3右下,4左下)
System.Drawing.Image image = System.Drawing.Image.FromFile(PicPath);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile(WaterMarkPath);
float[][] numArray2 = new float[5][];
float[] numArray3 = new float[5];
numArray3[0] = 1f; //www.
numArray2[0] = numArray3;
float[] numArray4 = new float[5];
numArray4[1] = 1f;
numArray2[1] = numArray4;
float[] numArray5 = new float[5];
numArray5[2] = 1f;
numArray2[2] = numArray5;
float[] numArray6 = new float[5];
numArray6[3] = ((float)WaterMarkLight) / 100f;
numArray2[3] = numArray6;
float[] numArray7 = new float[5];
numArray7[4] = 1f;
numArray2[4] = numArray7;
float[][] newColorMatrix = numArray2;
ColorMatrix matrix = new ColorMatrix(newColorMatrix);
ImageAttributes imageAttr = new ImageAttributes();
imageAttr.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
Graphics g = null;
if (IsPixelFormatIndexed(image.PixelFormat))
{
Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
g = Graphics.FromImage(image);
}
else
g = Graphics.FromImage(image);
switch (WaterMarkPos)
{
case 1:
g.DrawImage(copyImage, new Rectangle(0, 0, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 2:
g.DrawImage(copyImage, new Rectangle(0, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 3:
g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, 0, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 4:
g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
case 5:
g.DrawImage(copyImage, new Rectangle((image.Width - WaterMarkW) / 2, (image.Height - WaterMarkH) / 2, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
break;
}
g.Dispose();
image.Save(NewPicPath);
image.Dispose();
if (File.Exists(PicPath))
{
File.Delete(PicPath);
}
return newfilename;
}
///
/// 添加字体水印
///
/// 企业ID
/// 要加水印图片的路径
///
public static string LetterWaterMark(string filename, SanRenCMS.Model.WaterMarkConfig mwmc, string UpLoadPicPath)
{
string newfilename = string.Empty;
Font f;
string PicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + filename;
//HttpContext.Current.Response.Write(filename);
newfilename = Guid.NewGuid().ToString() + ".jpg";
//DateTime.Now.ToString("yyMMddhhmmss") + ".jpg";
string NewPicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + newfilename;
//HttpContext.Current.Response.Write(NewPicPath);
string WaterMarkStr = mwmc.WaterMarkWord;//水印文字
int WaterMarkFontSize = mwmc.WaterMarkWorkSize; //文字大小,单位PX
string WaterMarkFontName = mwmc.WaterMarkFont;// "华文细黑";//字体
string WaterMarkFontColor = mwmc.WaterMarkWordColor;// "009999";//字体颜色
bool WaterMarkIsBold = mwmc.isStrong == 1 ? true : false;//是否加粗
int WaterMarkPos = mwmc.WaterMarkPosition;//水印位置
System.Drawing.Image image = System.Drawing.Image.FromFile(PicPath);
Graphics g = null;
if (IsPixelFormatIndexed(image.PixelFormat))
{
Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
g = Graphics.FromImage(image);
}
else
g = Graphics.FromImage(image);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, 0, 0, image.Width, image.Height);
if (WaterMarkIsBold)
{
f = new Font(WaterMarkFontName, (float)WaterMarkFontSize, FontStyle.Bold);
}
else
{
f = new Font(WaterMarkFontName, (float)WaterMarkFontSize);
}
Brush b = new SolidBrush(ColorTranslator.FromHtml("#" + WaterMarkFontColor));
string addText = WaterMarkStr;
//switch (WaterMarkPos)
//{
// case 1:
// g.DrawString(addText, f, b, (float)0f, (float)0f);
// break;
// case 2:
// g.DrawString(addText, f, b, (float)0f, (float)0f);
// break;
// case 3:
// g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
// break;
// case 4:
// g.DrawImage(copyImage, new Rectangle(0, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr);
// break;
//}
g.DrawString(addText, f, b, (float)(image.Width / 2), (float)(image.Height / 2));
//g.DrawString(addText,f,b,
g.Dispose();
try
{
//HttpContext.Current.Response.Write(NewPicPath);
image.Save(NewPicPath, ImageFormat.Jpeg);
}
catch (Exception exx)
{
HttpContext.Current.Response.Write(exx.ToString());
}
finally
{
image.Dispose();
}
if (File.Exists(PicPath))
{
File.Delete(PicPath);
}
return newfilename;
}
}