You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1738 lines
66 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Diagnostics;
using System.Data;
using System.IO.Compression;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.Web;
using System.Management;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.Xml.Linq;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Collections;
using System.Net;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Xml;
using NetLibrary.Data;
using System.Data.Common;
using NetLibrary.Log;
namespace NetLibrary
{
public class CustomIO
{
#region 图片转成bate数组,MemoryStream流示例
public static byte[] GetPhoto(string filePath)
{
Bitmap bmp = new Bitmap(filePath);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();
byte[] photo = new byte[ms.Length - 1];
ms.Position = 0;
ms.Read(photo, 0, photo.Length - 1);
ms.Close();
return photo;
}
#endregion
#region bate数组转成图片,MemoryStream流示例
public static Bitmap GetPhoto(byte[] images)
{
if (images == null) return null;
MemoryStream ms = new MemoryStream();
ms.Write(images, 0, images.Length);
Bitmap bmp = new Bitmap(ms);
ms.Close();
return bmp;
}
#endregion
#region 读取图片
public static Bitmap GetBitmap(string FilePath)
{
Bitmap bmp = new Bitmap(FilePath);
Bitmap bmp2 = null;
//if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Undefined || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.DontCare || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppArgb1555 || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format1bppIndexed || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format4bppIndexed || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
//{
// bmp2 = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
//}
//else
//{
// bmp2 = new Bitmap(bmp.Width, bmp.Height, bmp.PixelFormat);
//}
bmp2 = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
bmp2.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
Graphics gp = Graphics.FromImage(bmp2);
gp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
gp.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
gp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gp.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
gp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gp.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
gp.DrawImage(bmp, 0, 0);
gp.Dispose();
bmp.Dispose();
return bmp2;
}
#endregion
#region 图片转byte数组
public static byte[] GetPhoto(Bitmap bmp)
{
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] photo = new byte[ms.Length - 1];
ms.Position = 0;
ms.Read(photo, 0, photo.Length - 1);
ms.Close();
return photo;
}
#endregion
#region 图片转成bate数组,MemoryStream流示例
public static byte[] GetPhoto(System.Drawing.Image img)
{
Bitmap bmp = new Bitmap(img);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();
byte[] photo = new byte[ms.Length - 1];
ms.Position = 0;
ms.Read(photo, 0, photo.Length - 1);
ms.Close();
return photo;
}
#endregion
#region 图片压缩_无损高质量
public static bool ImageCompress(string sFile, string outPath, int width, int height, int flag)
{
System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
System.Drawing.Image targetImg = new System.Drawing.Bitmap(width, height);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(targetImg))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.DrawImage(iSource, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, iSource.Width, iSource.Height), System.Drawing.GraphicsUnit.Pixel);
g.Dispose();
}
if (flag == 100)
{
targetImg.Save(outPath, ImageFormat.Jpeg);
iSource.Dispose();
targetImg.Dispose();
return true;
}
iSource.Dispose();
//ImageFormat tFormat = iSource.RawFormat;
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
targetImg.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径
}
else
{
targetImg.Save(outPath, ImageFormat.Jpeg);
}
return true;
}
catch
{
return false;
}
finally
{
targetImg.Dispose();
}
}
#endregion
#region 图片压缩_中质量
public static bool ImageCompress2(string sFile, string outPath, int width, int height, int flag)
{
System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
double ratio = 0d;
double myThumbWidth = 0d;
double myThumbHeight = 0d;
int xx = 0;
int yy = 0;
Bitmap targetImg;
if ((iSource.Width / Convert.ToDouble(width)) > (iSource.Height /
Convert.ToDouble(height)))
ratio = Convert.ToDouble(iSource.Width) / Convert.ToDouble(width);
else
ratio = Convert.ToDouble(iSource.Height) / Convert.ToDouble(height);
myThumbHeight = Math.Ceiling(iSource.Height / ratio);
myThumbWidth = Math.Ceiling(iSource.Width / ratio);
Size thumbSize = new Size(width, height);
targetImg = new Bitmap(width, height);
xx = (width - thumbSize.Width) / 2;
yy = (height - thumbSize.Height);
System.Drawing.Graphics g = Graphics.FromImage(targetImg);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(xx, yy, thumbSize.Width, thumbSize.Height);
g.DrawImage(iSource, rect, 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
if (flag == 100)
{
targetImg.Save(outPath, ImageFormat.Jpeg);
iSource.Dispose();
targetImg.Dispose();
return true;
}
iSource.Dispose();
//ImageFormat tFormat = iSource.RawFormat;
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
targetImg.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径
}
else
{
targetImg.Save(outPath, ImageFormat.Jpeg);
}
return true;
}
catch
{
return false;
}
finally
{
targetImg.Dispose();
}
}
#endregion
#region 图片压缩_只压缩质量
public static bool ImageCompress3(string sFile, string outPath, int flag)
{
System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径
}
else
{
iSource.Save(outPath, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
iSource.Dispose();
}
}
#endregion
#region 文件转成bate数组,MemoryStream流示例
public static byte[] GetOffice(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes(System.Convert.ToInt32(fs.Length));
br.Close();
fs.Close();
return photo;
}
#endregion
#region bate数组转成文件,FileStream流示例
public static void SetOffice(String filePath, byte[] photo)
{
try
{
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter br = new BinaryWriter(fs);
br.Write(photo);
br.Close();
fs.Close();
}
catch
{
}
}
#endregion
#region 查看文件
/// <summary>
/// 启用应用程序自身的进程查看文件
/// </summary>
/// <param name="fileName"></param>
public static void OpenFile(string fileName)
{
try
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = fileName;
process.StartInfo.Verb = "Open";
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = true;
process.Start();
}
catch
{
System.Windows.Forms.MessageBox.Show("文件已损坏或是权限不够");
}
}
#endregion
#region 时间化成秒
public static int TimeToSecond(DateTime Date, int IsAddDay)
{
//0前天,1当天,2后天
int a = 24 * 60 * 60;//一天的秒粉86400
int Hour = Date.Hour; //小时
int Minute = Date.Minute; //分钟
switch (IsAddDay)
{
case 0:
return (Hour * 60 + Minute) * 60;
case 1:
return (Hour * 60 + Minute) * 60 + a;
default:
break;
}
return 0;
}
#endregion
#region 秒化成时间
public static DateTime SecondToTime(int Date)
{
int a = 24 * 60 * 60;//一天的秒粉86400
int b = Date;
if (b >= a) b = b - a;
int Minute = b / 60; //分钟
int Hour = Minute / 60; //小时
Minute = Minute % 60;//真正的分钟
return new DateTime(2000, 1, 1, Hour, Minute, 0, 0);
}
#endregion
#region 时间格式化
//public static string ConvertTime(TimeSpan sp)
//{
//}
#endregion
#region 打开保存对话框
/// <summary>
/// 打开保存对话框
/// </summary>
/// <param name="filter">文件类型选择中出现的选择内容</param>
/// <param name="FileName">文件名称</param>
/// <param name="DefaultExt">文件默认扩展名</param>
/// <returns></returns>
public static string ShowSaveFileDialog(string filter, string FileName, string DefaultExt)
{
System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
dlg.AddExtension = true;
dlg.CheckPathExists = true;
dlg.DefaultExt = DefaultExt;
dlg.FilterIndex = 0;
dlg.Title = "保存";
dlg.FileName = FileName;
dlg.Filter = filter;
dlg.ValidateNames = true;
string FileName2 = "";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) FileName2 = dlg.FileName;
dlg.Dispose();
return FileName2;
}
#endregion
#region 打开读取对话框
/// <summary>
/// 打开读取对话框
/// </summary>
/// <param name="filter">文件类型选择中出现的选择内容txt files (*.txt)|*.txt|All files (*.*)|*.*</param>
/// <param name="DefaultExt">文件默认扩展名</param>
/// <returns></returns>
public static string ShowOpenFileDialog(string filter, string DefaultExt)
{
System.Windows.Forms.OpenFileDialog openfile = new System.Windows.Forms.OpenFileDialog();
openfile.AddExtension = true;
//openfile.DefaultExt = "xls";
openfile.Filter = filter;
openfile.DefaultExt = DefaultExt;
//openfile.FilterIndex = 0;
if (openfile.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return "";
return openfile.FileName;
}
#endregion
#region 删除文件夹及下面所有文件
public static void DeleteFile(string Directory)
{
CustomIO obj = new CustomIO();
obj.DeleteFileTree(Directory, true, 0);
foreach (string s in obj.files)
{
System.IO.Directory.Delete(s);
}
}
List<string> files = new List<string>();
void DeleteFileTree(string dir, bool showFiles, int level)
{
try
{
if (showFiles == true)
{
foreach (string fname in Directory.GetFiles(dir))
{
System.IO.File.Delete(fname);
}
}
foreach (string subdir in Directory.GetDirectories(dir))
{
DeleteFileTree(subdir, showFiles, level + 1);
}
}
catch
{
}
}
void GetDirectory(string dir, int level)
{
try
{
foreach (string subdir in Directory.GetDirectories(dir))
{
files.Insert(0, subdir);
GetDirectory(subdir, level + 1);
}
}
catch
{
}
}
#endregion
#region 返回文件校验码
public static string GetFileCheckCode(string FilePath)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192);
byte[] hash = md5.ComputeHash(fs);
StringBuilder sb = new StringBuilder();
foreach (byte byt in hash)
{
sb.Append(String.Format("{0:X2}", byt));
}
return sb.ToString();
}
#endregion
#region 返回数组校验码
public static string GetCheckCode(byte[] bytes)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
MemoryStream fs = new MemoryStream(bytes);
byte[] hash = md5.ComputeHash(fs);
StringBuilder sb = new StringBuilder();
foreach (byte byt in hash)
{
sb.Append(String.Format("{0:X2}", byt));
}
return sb.ToString();
}
#endregion
#region 判断操作系统
public static string GetOSVersionString()
{
OperatingSystem os = System.Environment.OSVersion;
if (os.Version.Major == 5 && os.Version.Minor == 1) return "XP";
if (os.Version.Major == 5 && os.Version.Minor == 2) return "2003";
return "";
}
#endregion
#region 读取U盘序列号
public static List<string> GetUKey()
{
ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = cimobject.GetInstances();
List<string> listkey = new List<string>();
foreach (ManagementObject mo in moc)
{
if (mo.Properties["InterfaceType"].Value.ToString() != "USB") continue;
string[] info = mo.Properties["PNPDeviceID"].Value.ToString().Split('&');
string[] xx = info[3].Split('\\');
listkey.Add(xx[1]);
}
return listkey;
}
#endregion
#region 条码
public static Bitmap CreateCodeLogo(string code)
{
long len = code.Length;
string lastString = "";
char[] list = new char[len + 1];
list = code.ToCharArray();
for (int i = 0; i < list.Length; i++)
{
lastString += ConvertToBinaryString(list[i].ToString());
}
char[] numList = new char[lastString.Length + 1];
numList = lastString.ToCharArray();
Bitmap image = new Bitmap(200, 140);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
Pen penBlack = new Pen(Color.FromArgb(255, 0, 0, 0), 2.5F);
Pen penWhite = new Pen(Color.White, 2.5F);
int j = 0;
for (float k = 10; j < numList.Length; k += 2F, j++)
{
if (numList[j].ToString() == "1")
{
g.DrawLine(penBlack, k, 10, k, 110);
}
else
{
g.DrawLine(penWhite, k, 10, k, 110);
}
if (j % 4 == 0)
{
g.DrawString(list[j / 4].ToString(), new System.Drawing.Font("Courier New", 12), new SolidBrush(Color.Red), k, 112);
}
}
return image;
}
#endregion
#region 将字符串数值转换为二进制字符串数值
public static string ConvertToBinaryString(string buf)
{
int[] temp = new int[20];
string binary;
int val = 0, i = 0, j;
//先将字符转化为十进制数
try
{
val = Convert.ToInt32(buf);
}
catch
{
val = 0;
}
if (val == 0)
{
return ("0000");
}
i = 0;
while (val != 0)
{
temp[i++] = val % 2;
val /= 2;
}
binary = "";
for (j = 0; j <= i - 1; j++)
{
binary += (char)(temp[i - j - 1] + 48);
}
if (binary.Length < 4) //如果小于4位左边补零
{
int len = 4 - binary.Length;
string str = "";
while (len > 0)
{
str += "0";
len--;
}
binary = str + binary;
}
return (binary);
}
#endregion
#region 压缩
public static void ZipCompress(string filePath, string zipPath)
{
FileStream sourceFile = File.OpenRead(filePath);
FileStream destinationFile = File.Create(zipPath);
byte[] buffer = new byte[sourceFile.Length];
GZipStream zip = null;
try
{
sourceFile.Read(buffer, 0, buffer.Length);
zip = new GZipStream(destinationFile, CompressionMode.Compress);
zip.Write(buffer, 0, buffer.Length);
}
catch
{
}
finally
{
zip.Close();
sourceFile.Close();
destinationFile.Close();
}
}
#endregion
#region 解压缩
public static void ZipDecompress(string zipPath, string filePath)
{
FileStream sourceFile = File.OpenRead(zipPath);
string path = filePath.Replace(Path.GetFileName(filePath), "");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
FileStream destinationFile = File.Create(filePath);
GZipStream unzip = null;
byte[] buffer = new byte[sourceFile.Length];
try
{
unzip = new GZipStream(sourceFile, CompressionMode.Decompress, true);
int numberOfBytes = unzip.Read(buffer, 0, buffer.Length);
destinationFile.Write(buffer, 0, numberOfBytes);
}
catch
{
}
finally
{
sourceFile.Close();
destinationFile.Close();
unzip.Close();
}
}
#endregion
#region 备份数据库
public static void BackDataBase(string databaseName, string filePath)
{
Database db = DatabaseFactory.CreateDatabase();
db.DataBaseName = "master";
DbCommand cmd = db.GetSqlStringCommand("BACKUP DATABASE [" + databaseName + "] TO DISK = N'" + filePath + "' WITH NOFORMAT, NOINIT, NAME = N'" + databaseName + "-完整 数据库 备份', SKIP, NOREWIND, NOUNLOAD, STATS = 10");
cmd.CommandTimeout = int.MaxValue;
db.ExecuteNonQuery(cmd);
}
#endregion
#region 还原数据库
public static void RestoreDatabase(string databaseName, string filePath)
{
string filename = System.IO.Path.GetFileNameWithoutExtension(filePath);
string LogicalName_mdf = "";
string LogicalName_ldf = "";
string filePath_mdf = "";
string filePath_ldf = "";
KillSPID(databaseName);
Database db = DatabaseFactory.CreateDatabase();
db.DataBaseName = "master";
DbCommand cmd = db.GetSqlStringCommand("select fileid,filename from sysaltfiles where dbid=(select dbid from sysdatabases where name=@name) order by fileid");
db.AddInParameter(cmd, "@name", DbType.String, databaseName);
DataTable tb = db.ExecuteDataTable(cmd);
filePath_mdf = tb.Rows[0]["filename"].ToString().Trim();
filePath_ldf = tb.Rows[1]["filename"].ToString().Trim();
cmd = db.GetSqlStringCommand("RESTORE FILELISTONLY FROM DISK = N'" + filePath + "'");
tb = db.ExecuteDataTable(cmd);
LogicalName_mdf = tb.Rows[0]["LogicalName"].ToString().Trim();
LogicalName_ldf = tb.Rows[1]["LogicalName"].ToString().Trim();
cmd = db.GetSqlStringCommand("RESTORE DATABASE [" + databaseName + "] FROM DISK = N'" + filePath + "' WITH MOVE '" + LogicalName_mdf + "' TO '" + filePath_mdf + "',MOVE '" + LogicalName_ldf + "' TO '" + filePath_ldf + "',FILE = 1, NOUNLOAD, REPLACE, STATS = 10");
cmd.CommandTimeout = int.MaxValue;
db.ExecuteNonQuery(cmd);
}
#endregion
#region 关闭当前连接数据库的连接进程
/// <summary>
/// 关闭当前连接数据库的连接进程
/// </summary>
/// <param name="DBName">要关闭进程的数据库名称</param>
public static void KillSPID(string databaseName)
{
Database db = DatabaseFactory.CreateDatabase();
db.DataBaseName = "master";
DbCommand cmd = db.GetSqlStringCommand("select spid from master..sysprocesses where dbid=db_id('" + databaseName + "')");
cmd.CommandTimeout = int.MaxValue;
DataTable tb = db.ExecuteDataTable(cmd);
foreach (DataRow row in tb.Rows)
{
cmd = db.GetSqlStringCommand("kill " + row["spid"].ToString());
db.ExecuteNonQuery(cmd);
}
}
#endregion
#region 是否安装了Winrar
/// <summary>
/// 是否安装了Winrar
/// </summary>
/// <returns></returns>
public static bool RarExists()
{
RegistryKey the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
return !string.IsNullOrEmpty(the_Reg.GetValue("").ToString());
}
#endregion
#region 打包成Rar
/// <summary>
/// 打包成Rar
/// </summary>
/// <param name="patch"></param>
/// <param name="rarPatch"></param>
/// <param name="rarName"></param>
public static void RarCompress(string patch, string rarPatch)
{
string the_rar = "";
RegistryKey the_Reg;
object the_Obj;
string the_Info;
ProcessStartInfo the_StartInfo;
Process the_Process;
try
{
the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
if (the_Reg != null)
{
the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
}
//if (Directory.Exists(patch) == false)
//{
// Directory.CreateDirectory(patch);
//}
//命令参数
//the_Info = " a " + rarName + " " + @"C:Test?70821.txt"; //文件压缩
the_Info = "a \"" + rarPatch + "\" \"" + System.IO.Path.GetFileName(patch) + "\" -r";
if (string.IsNullOrEmpty(the_rar) == true) the_rar = "C:/Program Files/WinRAR/WinRAR.exe";
the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
//打包文件存放目录
the_StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(patch);
the_StartInfo.UseShellExecute = false;
the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
the_Process.WaitForExit();
the_Process.Close();
}
catch (Exception ex)
{
NetLibrary.Log.ErrorFollow.TraceWrite("RarCompress()", ex.StackTrace, ex.Message);
}
}
#endregion
#region 解压
/// <summary>
/// 解压
/// </summary>
/// <param name="unRarPatch"></param>
/// <param name="rarPatch"></param>
/// <param name="rarName"></param>
/// <returns></returns>
public static void RarDecompress(string unRarPatch, string rarPatch, string rarName)
{
string the_rar;
RegistryKey the_Reg;
object the_Obj;
string the_Info;
try
{
the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
//the_rar = the_rar.Substring(1, the_rar.Length - 7);
if (Directory.Exists(unRarPatch) == false)
{
Directory.CreateDirectory(unRarPatch);
}
the_Info = "x \"" + rarName + "\" \"" + unRarPatch + "\" -y";
ProcessStartInfo the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
the_StartInfo.WorkingDirectory = rarPatch;//获取压缩包路径
Process the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
the_Process.WaitForExit();
the_Process.Close();
}
catch (Exception ex)
{
NetLibrary.Log.ErrorFollow.TraceWrite("RarDecompress()", ex.StackTrace, ex.Message);
}
}
#endregion
#region 下载文件
public static void DownFile(HttpResponse Response, string FilePath, string Name)
{
if (FilePath == "") return;
if (FilePath.Substring(0, 1) == "/") FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath.Substring(1);
if (FilePath.Substring(0, 3) == "../") FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath.Substring(3);
//FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath;
Response.Clear();
Response.ClearHeaders();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Name, System.Text.Encoding.GetEncoding("utf-8")));
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文
Response.ContentType = "application/octet-stream";
if (Path.GetExtension(FilePath) == ".doc") Response.ContentType = "application/ms-word";
if (Path.GetExtension(FilePath) == ".xls") Response.ContentType = "application/ms-excel";
if (System.IO.File.Exists(FilePath) == true)
{
FileInfo fi = new FileInfo(FilePath);
FileStream fs = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
try
{
fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
Response.AppendHeader("Content-Length", fs.Length.ToString());
dataToRead = fs.Length;
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = fs.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
Response.End();
}
catch { }
finally
{
if (fs != null)
{
fs.Close();
}
Response.End();
}
}
}
#endregion
#region Http请求
public static string HttpRequest(string url, string Method, out string ErrorMessage)
{
try
{
ErrorMessage = "";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = Method; //GET,POST
myRequest.ContentType = "application/x-www-form-urlencoded";
//myRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; qihu theworld)";
myRequest.Headers.Add("Accept-Language: zh-CN");
myRequest.Headers["Pragma"] = "no-cache"; //禁用缓存
myRequest.Headers["Cache-Control"] = "no-cache"; //禁用缓存
myRequest.Timeout = 3 * 60 * 1000;
//获得接口返回值
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8);
string content = reader.ReadToEnd();
reader.Close();
myResponseStream.Close();
myResponse.Close();
return content;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
ErrorMessage = ex.Message;
}
return "";
}
#endregion
#region Http请求2
public static string HttpRequest2(string url, string Method, string ContentType, List<string> ListHeader,Version ver, byte[] bytes,out string ErrorMessage)
{
try
{
ErrorMessage = "";
if (string.IsNullOrEmpty(ContentType) == true) ContentType = "application/x-www-form-urlencoded";
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = Method; //GET,POST
myRequest.ContentType = ContentType;
myRequest.KeepAlive = true;
//myRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; qihu theworld)";
//myRequest.Headers.Add("Accept-Language: zh-CN");
// myRequest.Headers["Pragma"] = "no-cache"; //禁用缓存
// myRequest.Headers["Cache-Control"] = "no-cache"; //禁用缓存
myRequest.Timeout = 3 * 60 * 1000;
if (ver != null)
myRequest.ProtocolVersion = ver;
if (ListHeader != null)
{
foreach (var item in ListHeader)
{
myRequest.Headers.Add(item);
}
}
if (bytes != null && bytes.Length > 0)
{
//myRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
Stream stream = myRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
else
myRequest.ContentLength = 0;
//获得接口返回值
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8);
string content = reader.ReadToEnd();
reader.Close();
myResponseStream.Close();
myRequest.Abort();
myResponse.Close();
return content;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
ErrorMessage = ex.Message;
}
return "";
}
#endregion
#region OneWordHttp请求
public static string OneWordHttpRequest(string url, string Method, string Code, string Pwd, byte[] bytes, out string ErrorMessage)
{
try
{
Random rd = new Random();
string sj = DateTime.Now.ToString("hhmmss");
sj = rd.Next(100, 1000000).ToString() + sj + rd.Next(1000, 10000000).ToString();
ErrorMessage = "";
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = Method; //GET,POST
myRequest.ContentType = "application/json";
//myRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; qihu theworld)";
myRequest.Headers.Add("Authorization", "Hc-OweDeveloper " + Code + ";" + Pwd + ";" + sj);
myRequest.Headers["Pragma"] = "no-cache"; //禁用缓存
myRequest.Headers["Cache-Control"] = "no-cache"; //禁用缓存
myRequest.Timeout = 3 * 60 * 1000;
myRequest.ProtocolVersion = HttpVersion.Version11;
if (bytes != null && bytes.Length > 0)
{
//myRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
Stream stream = myRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
//获得接口返回值
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8);
string content = reader.ReadToEnd();
reader.Close();
myResponseStream.Close();
myResponse.Close();
return content;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
ErrorMessage = ex.Message;
}
return "";
}
#endregion
#region OneWordHttp请求保存成pdf
public static string OneWordPdfHttpRequest(string url, string Method, string Code, string Pwd, byte[] bytes, out string ErrorMessage)
{
try
{
Random rd = new Random();
string sj = DateTime.Now.ToString("hhmmss");
sj = rd.Next(100, 1000000).ToString() + sj + rd.Next(1000, 10000000).ToString();
ErrorMessage = "";
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = Method; //GET,POST
myRequest.ContentType = "application/json";
//myRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; qihu theworld)";
myRequest.Headers.Add("Authorization", "Hc-OweDeveloper " + Code + ";" + Pwd + ";" + sj);
myRequest.Headers["Pragma"] = "no-cache"; //禁用缓存
myRequest.Headers["Cache-Control"] = "no-cache"; //禁用缓存
myRequest.Timeout = 3 * 60 * 1000;
myRequest.ProtocolVersion = HttpVersion.Version11;
if (bytes != null && bytes.Length > 0)
{
//myRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
Stream stream = myRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
//获得接口返回值
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8);
string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
if (System.IO.Directory.Exists(dir) == false) System.IO.Directory.CreateDirectory(dir);
string fname = Guid.NewGuid().ToString() + ".pdf";
string filePath = dir + "/" + fname;
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = myResponseStream.Read(data, 0, data.Length);
if (size > 0)
{
fileStream.Write(data, 0, size);
}
else
{
break;
}
}
}
reader.Close();
myResponseStream.Close();
myRequest.Abort();
myResponse.Close();
return filePath;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
ErrorMessage = ex.Message;
}
return "";
}
#endregion
#region 转换成Url参数化字符串
public static string param<TResult>(TResult T) where TResult : class
{
Type type = typeof(TResult);
string ss = "";
Array.ForEach<PropertyInfo>(type.GetProperties(), item =>
{
//Type columnType = item.PropertyType;
//if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
//{
// columnType = item.PropertyType.GetGenericArguments()[0];
//}
string value = Convert.ToString(item.GetValue(T, null));
if (string.IsNullOrEmpty(value) == false)
{
value = System.Web.HttpUtility.UrlEncode(value, Encoding.GetEncoding("utf-8"));
ss += "&" + item.Name + "=" + value;
}
});
ss = ss.Substring(1);
return ss;
}
#endregion
#region 压缩SharpZipLib
public static void ZipLibCompress(string strDirectory, string zipedFile)
{
using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))
{
using (ZipOutputStream s = new ZipOutputStream(ZipFile))
{
ZipSetp(strDirectory, s, "");
}
}
}
private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)
{
if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
{
strDirectory += Path.DirectorySeparatorChar;
}
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strDirectory);
foreach (string file in filenames)// 遍历所有的文件和目录
{
if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
{
string pPath = parentPath;
pPath += file.Substring(file.LastIndexOf("\\") + 1);
pPath += "\\";
ZipSetp(file, s, pPath);
}
else // 否则直接压缩文件
{
//打开压缩文件
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + 1);
ZipEntry entry = new ZipEntry(fileName);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
}
}
#endregion
#region 解压缩SharpZipLib
/// <param name="zipedFile">The ziped file.</param>
/// <param name="strDirectory">The STR directory.</param>
/// <param name="password">zip 文件的密码。</param>
/// <param name="overWrite">是否覆盖已存在的文件。</param>
public static void ZipLibDecompress(string zipedFile, string strDirectory, string password, bool overWrite)
{
if (strDirectory == "")
strDirectory = Directory.GetCurrentDirectory();
if (!strDirectory.EndsWith("\\"))
strDirectory = strDirectory + "\\";
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
{
s.Password = password;
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = "";
string pathToZip = "";
pathToZip = theEntry.Name;
if (pathToZip != "")
directoryName = Path.GetDirectoryName(pathToZip) + "\\";
string fileName = Path.GetFileName(pathToZip);
Directory.CreateDirectory(strDirectory + directoryName);
if (fileName != "")
{
if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
{
using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
streamWriter.Write(data, 0, size);
else
break;
}
streamWriter.Close();
}
}
}
}
s.Close();
}
}
#endregion
#region 复制文件目录到新目录
public static void CopyDirectory(string OldDirectory, string NewDirectory)
{
if (Directory.Exists(NewDirectory) == false) Directory.CreateDirectory(NewDirectory);
string[] files = Directory.GetFiles(OldDirectory);
foreach (string fname in files)
{
string fileName = Path.GetFileName(fname);
string newFileName = NewDirectory + "/" + fileName;
File.Copy(fname, newFileName, true);
}
foreach (string subdir in Directory.GetDirectories(OldDirectory))
{
string NewDirectory2 = NewDirectory + subdir.Substring(OldDirectory.Length);
CopyDirectory(subdir, NewDirectory2);
}
}
#endregion
#region 读取XML属性值
public static string GetXmlAttribute(XElement doc, string Name)
{
if (doc.Attribute(Name) == null) return "";
return doc.Attribute(Name).Value;
}
#endregion
#region 读取XML属性值
public static string GetXmlAttribute(XmlNode doc, string Name)
{
if (doc.Attributes[Name] == null) return "";
return doc.Attributes[Name].Value;
}
#endregion
#region 读取XML内容值
public static string GetXmlElement(XElement doc, string Name)
{
if (doc.Element(Name) == null) return "";
return doc.Element(Name).Value;
}
#endregion
#region 读取Key
public static string GetKeyValues(Dictionary<string, string> ReceiveModel, string key)
{
string val = "";
key = key.ToUpper();
ReceiveModel.TryGetValue(key, out val);
if (val == null) val = "";
return val;
}
#endregion
#region 安装服务
public static void InstallService(string filepath)
{
try
{
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = filepath;
Hashtable stateSaver = new System.Collections.Hashtable();
myAssemblyInstaller.Install(stateSaver);
myAssemblyInstaller.Commit(stateSaver);
myAssemblyInstaller.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("安装服务失败!");
}
}
#endregion
#region 读取FTP文件夹
public static void FtpGetDirectory(string Url, string UserName, string PassWord, out List<string> ListDirectory, out List<string> ListFile)
{
if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url;
List<string> ListModel = new List<string>();
List<string> ListModel2 = new List<string>();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url));
ftp.Credentials = new NetworkCredential(UserName, PassWord);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
Regex replaceSpace = new Regex(@"\s{1,}", RegexOptions.IgnoreCase);
string line = "";
while (true)
{
line = reader.ReadLine();
if (line == null) break;
int index = line.IndexOf("<DIR>");
line = replaceSpace.Replace(line, ",").Trim();
string[] ss = line.Split(',');
line = "";
for (int i = 3; i < ss.Length; i++)
{
line += ss[i] + " ";
}
line = line.TrimEnd();
if (index == -1)
{
ListModel.Add(line);
}
else
{
ListModel2.Add(line);
}
}
reader.Close();
response.Close();
ListDirectory = ListModel2;
ListFile = ListModel;
}
#endregion
#region 创建FTP文件夹
public static void FtpCreateDirectory(string Url, string UserName, string PassWord)
{
if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url;
FtpWebRequest ser;
ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url));
ser.Method = WebRequestMethods.Ftp.MakeDirectory;
ser.Credentials = new NetworkCredential(UserName, PassWord);
FtpWebResponse response = (FtpWebResponse)ser.GetResponse();
response.Close();
}
#endregion
#region FTP文件改名
public static void FtpReFileName(string Url, string UserName, string PassWord, string FileName, string newFileName)
{
if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url;
FtpWebRequest ser;
ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + FileName));
ser.Method = WebRequestMethods.Ftp.Rename;
ser.Credentials = new NetworkCredential(UserName, PassWord);
ser.RenameTo = newFileName;
FtpWebResponse response = (FtpWebResponse)ser.GetResponse();
response.Close();
}
#endregion
#region FTP删除目录
public static void FtpDeleteDirectory(string Url, string UserName, string PassWord)
{
if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url;
FtpWebRequest ser;
ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url));
ser.Method = WebRequestMethods.Ftp.RemoveDirectory;
ser.Credentials = new NetworkCredential(UserName, PassWord);
FtpWebResponse response = (FtpWebResponse)ser.GetResponse();
response.Close();
}
#endregion
#region FTP删除文件
public static void FtpDeleteFile(string Url, string UserName, string PassWord, string FileName)
{
if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url;
FtpWebRequest ser;
ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + FileName));
ser.Method = WebRequestMethods.Ftp.DeleteFile;
ser.Credentials = new NetworkCredential(UserName, PassWord);
FtpWebResponse response = (FtpWebResponse)ser.GetResponse();
response.Close();
}
#endregion
#region FTP上传文件
public static void FtpUploadFile(string Url, string UserName, string PassWord, string FilePath)
{
if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url;
FileStream fileStream = File.Open(FilePath, FileMode.Open);
FtpWebRequest ser;
ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + Path.GetFileName(FilePath)));
ser.Method = WebRequestMethods.Ftp.UploadFile;
ser.Credentials = new NetworkCredential(UserName, PassWord);
ser.UseBinary = true;
ser.KeepAlive = false;
Stream requestStream = ser.GetRequestStream();
ser.ContentLength = fileStream.Length;
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Close();
fileStream.Close();
}
#endregion
#region FTP下载文件
public static void FtpDownloadFile(string Url, string UserName, string PassWord, string FileName, string SaveDirectory)
{
if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url;
FtpWebRequest ser;
ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + FileName));
ser.Method = WebRequestMethods.Ftp.DownloadFile;
ser.Credentials = new NetworkCredential(UserName, PassWord);
FtpWebResponse response = (FtpWebResponse)ser.GetResponse();
Stream requestStream = response.GetResponseStream();
FileStream outputStream = new FileStream(SaveDirectory + "/" + FileName, FileMode.Create);
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = requestStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = requestStream.Read(buffer, 0, bufferSize);
}
requestStream.Close();
outputStream.Close();
response.Close();
}
#endregion
#region 把对象序列化成键值
public static string SerializeKeyValue<T>(T Model)
{
return "";
}
#endregion
#region 创建文件夹路径
public static void CreateDirectory(string FilePath)
{
string dir = Path.GetDirectoryName(FilePath);
if (string.IsNullOrEmpty(dir) == true) return;
dir = dir.Replace("\\", "/");
string[] ss = dir.Split('/');
string dir2 = "";
foreach (string item in ss)
{
if (string.IsNullOrEmpty(item) == true) continue;
if (dir2 == "") { dir2 += item; }
else { dir2 += "/" + item; }
if (Directory.Exists(dir2) == false) Directory.CreateDirectory(dir2);
}
}
#endregion
#region 读取文件夹下所有文件
public static void GetListFile(string dir, List<string> ListModel)
{
if (Directory.Exists(dir) == false) return;
string[] files = Directory.GetFiles(dir);
foreach (string fname in files)
{
ListModel.Add(fname);
}
foreach (string subdir in Directory.GetDirectories(dir))
{
GetListFile(subdir, ListModel);
}
}
#endregion
#region 将Base64编码的文本转换成普通文本
/// <summary>
/// 将Base64编码的文本转换成普通文本
/// </summary>
/// <param name="base64">Base64编码的文本</param>
/// <returns></returns>
public static string Base64StringToString(string base64)
{
//char[] charBuffer = base64.ToCharArray();
//byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
//return (new UnicodeEncoding()).GetString(bytes);
byte[] c = Convert.FromBase64String(base64);
string a = System.Text.Encoding.UTF8.GetString(c);
return a;
}
#endregion
#region 将Base64编码文本转换成Byte[]
/// <summary>
/// 将Base64编码文本转换成Byte[]
/// </summary>
/// <param name="base64">Base64编码文本</param>
/// <returns></returns>
public static Byte[] Base64ToBytes(string base64)
{
char[] charBuffer = base64.ToCharArray();
byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
return bytes;
}
#endregion
#region bate数组转成文件,FileStream流示例
public static void SetImage(String filePath, byte[] photo)
{
try
{
MemoryStream buf = new MemoryStream(photo);
Image image = Image.FromStream(buf, true);
image.Save(filePath, image.RawFormat);
buf.Dispose();
image.Dispose();
}
catch
{
}
}
#endregion
#region bate数组转成文件,FileStream流示例
public static void SetImage(String filePath, string ImageBase64)
{
try
{
byte[] bytes = CustomIO.Base64ToBytes(ImageBase64);
CustomIO.SetImage(filePath, bytes);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("保存图片", "ImageBase64", ex.Message);
}
}
#endregion
}
#region 上传文件信息对象
public class UserFileInfo
{
private string m_OldFileName;
/// <summary>
/// 目录+文件名
/// </summary>
public string OldFileName
{
get { return m_OldFileName; }
set { m_OldFileName = value; }
}
private string m_FileName;
/// <summary>
/// 目录+文件名
/// </summary>
public string FileName
{
get { return m_FileName; }
set { m_FileName = value; }
}
private string m_Extension;
/// <summary>
/// 文件扩展名
/// </summary>
public string Extension
{
get { return m_Extension; }
set { m_Extension = value; }
}
/// <summary>
/// 文件大小名称
/// </summary>
public string FileSizeName
{
get { return ConvertByte(FileSize); }
}
private long m_FileSize;
/// <summary>
/// 文件大小
/// </summary>
public long FileSize
{
get { return m_FileSize; }
set { m_FileSize = value; }
}
#region 转换计量单位
string ConvertByte(long seek)
{
if (seek > 1024 * 1024 * 1024)
{
return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("f2") + "GB";
}
if (seek > 1024 * 1024)
{
return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("f2") + "MB";
}
if (seek > 1024)
{
return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024)).ToString("f2") + "KB";
}
return seek.ToString() + "Byte";
}
#endregion
#region 返回数据
public static List<UserFileInfo> GetUserFileInfo(string infoString, string NewDirectoryName)
{
//文件夹不存在,创建文件夹
string ServerDirectoryPath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName;
if (!Directory.Exists(ServerDirectoryPath))
{
Directory.CreateDirectory(ServerDirectoryPath);
}
List<UserFileInfo> list = new List<UserFileInfo>();
string[] ss = infoString.Split(',');
foreach (string s in ss)
{
string[] sss = s.Split('♀');
string filePath = AppDomain.CurrentDomain.BaseDirectory + sss[0];
string ServerfilePath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName + "/" + System.IO.Path.GetFileName(sss[0]);
if (filePath != ServerfilePath) System.IO.File.Move(filePath, ServerfilePath);
FileInfo file = new FileInfo(filePath);
UserFileInfo uf = new UserFileInfo();
uf.OldFileName = sss[1];
uf.FileName = NewDirectoryName + "/" + System.IO.Path.GetFileName(sss[0]);
uf.FileSize = file.Length;
uf.Extension = file.Extension;
list.Add(uf);
}
return list;
}
#endregion
#region 返回数据(广济需求)
public static List<UserFileInfo> GetUserFileInfo_ForGuangJi(string infoString, string NewDirectoryName)
{
//文件夹不存在,创建文件夹
string ServerDirectoryPath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName;
if (!Directory.Exists(ServerDirectoryPath))
{
Directory.CreateDirectory(ServerDirectoryPath);
}
List<UserFileInfo> list = new List<UserFileInfo>();
string[] ss = infoString.Split(',');
foreach (string s in ss)
{
string[] sss = s.Split('♀');
string filePath = AppDomain.CurrentDomain.BaseDirectory + sss[0];
string OldName = System.IO.Path.GetFileName(sss[1]);
int index1 = OldName.LastIndexOf('.');
string NewFileName = OldName.Substring(0, index1) + DateTime.Now.ToString().Replace(':', '-') + OldName.Substring(index1);
string ServerfilePath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName + "/" + NewFileName;
UserFileInfo uf = new UserFileInfo();
FileInfo file = new FileInfo(filePath);
uf.OldFileName = sss[1];
uf.FileName = NewDirectoryName + "/" + NewFileName;
uf.FileSize = file.Length;
uf.Extension = file.Extension;
if (filePath != ServerfilePath) System.IO.File.Move(filePath, ServerfilePath);
list.Add(uf);
}
return list;
}
#endregion
}
#endregion
}