using CsharpHttpHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using Newtonsoft.Json;
namespace PCRobot.Utils
{
///
/// 生成计算机的16字节唯一标识码
/// Example: 4986-8FD5-EE85-69D3-FE52-8CF7-395D-E4A9
///
internal class FingerPrint
{
private static string fingerPrint = string.Empty;
public static string Value()
{
if (string.IsNullOrEmpty(fingerPrint))
fingerPrint = GetHash($"CPU >> {cpuId()}|BIOS >> {biosId()}|BASE >> {baseId()}|DISK >> {diskId()}|VIDEO >> {videoId()}|MAC >> {macId()}|PATH >> {Environment.CurrentDirectory}");
return fingerPrint;
}
private static string GetHash(string s)
{
try
{
MD5 sec = new MD5CryptoServiceProvider();
ASCIIEncoding enc = new ASCIIEncoding();
byte[] bt = enc.GetBytes(s);
return GetHexString(sec.ComputeHash(bt));
}
catch (Exception)
{ }
return string.Empty;
}
private static string GetHexString(byte[] bt)
{
var s = string.Empty;
try
{
for (int i = 0; i < bt.Length; i++)
{
byte b = bt[i];
int n, n1, n2;
n = (int)b;
n1 = n & 15;
n2 = (n >> 4) & 15;
if (n2 > 9)
s += ((char)(n2 - 10 + (int)'A')).ToString();
else
s += n2.ToString();
if (n1 > 9)
s += ((char)(n1 - 10 + (int)'A')).ToString();
else
s += n1.ToString();
if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
}
}
catch (Exception)
{ }
return s;
}
#region Original Device ID Getting Code
//Return a hardware identifier
private static string identifier(string wmiClass, string wmiProperty, string wmiMustBeTrue)
{
var result = string.Empty;
try
{
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
if (mo[wmiMustBeTrue].ToString() == "True")
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
}
}
catch (Exception)
{ }
return result;
}
//Return a hardware identifier
private static string identifier(string wmiClass, string wmiProperty)
{
var result = string.Empty;
try
{
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
}
catch (Exception ex)
{ }
return result;
}
private static string cpuId()
{
//Uses first CPU identifier available in order of preference
//Don't get all identifiers, as it is very time consuming
try
{
string retVal = identifier("Win32_Processor", "UniqueId");
if (retVal == "") //If no UniqueID, use ProcessorID
{
retVal = identifier("Win32_Processor", "ProcessorId");
if (retVal == "") //If no ProcessorId, use Name
{
retVal = identifier("Win32_Processor", "Name");
if (retVal == "") //If no Name, use Manufacturer
{
retVal = identifier("Win32_Processor", "Manufacturer");
}
//Add clock speed for extra security
retVal += identifier("Win32_Processor", "MaxClockSpeed");
}
}
return retVal;
}
catch (Exception)
{ }
return string.Empty;
}
//BIOS Identifier
private static string biosId()
{
try
{
return identifier("Win32_BIOS", "Manufacturer")
+ identifier("Win32_BIOS", "SMBIOSBIOSVersion")
+ identifier("Win32_BIOS", "IdentificationCode")
+ identifier("Win32_BIOS", "SerialNumber")
+ identifier("Win32_BIOS", "ReleaseDate")
+ identifier("Win32_BIOS", "Version");
}
catch (Exception)
{ }
return string.Empty;
}
//Main physical hard drive ID
private static string diskId()
{
try
{
return identifier("Win32_DiskDrive", "Model")
+ identifier("Win32_DiskDrive", "Manufacturer")
+ identifier("Win32_DiskDrive", "Signature")
+ identifier("Win32_DiskDrive", "TotalHeads");
}
catch (Exception)
{ }
return string.Empty;
}
//Motherboard ID
private static string baseId()
{
try
{
return identifier("Win32_BaseBoard", "Model")
+ identifier("Win32_BaseBoard", "Manufacturer")
+ identifier("Win32_BaseBoard", "Name")
+ identifier("Win32_BaseBoard", "SerialNumber");
}
catch (Exception)
{ }
return string.Empty;
}
//Primary video controller ID
private static string videoId()
{
try
{
return identifier("Win32_VideoController", "DriverVersion")
+ identifier("Win32_VideoController", "Name");
}
catch (Exception)
{ }
return string.Empty;
}
//First enabled network card ID
private static string macId()
{
try
{
return identifier("Win32_NetworkAdapterConfiguration",
"MACAddress", "IPEnabled");
}
catch (Exception ex)
{ }
return string.Empty;
}
#endregion
}
///
/// 企业Cdn文件类型
///
public enum QyCdnFileType
{
图片_视频 = 2,
语音 = 5,
}
///
/// 常用文件后缀
///
public enum FileSuffixType
{
jpg = 0,
png = 1,
gif = 2,
mp4 = 3,
txt = 4,
doc = 5,
ico = 6,
rar = 7,
silk = 8,
mp3 = 9,
}
public static class Common
{
///
/// 下载文件
///
///
///
///
public static bool DownFile(string url, string savePath)
{
try
{
if (!url.Trim().StartsWith("http", StringComparison.CurrentCultureIgnoreCase | StringComparison.OrdinalIgnoreCase) && File.Exists(url))
{
File.Copy(url, savePath, true);
return true;
}
WebClient client = new WebClient();
client.DownloadFile(url, savePath);
}
catch (Exception ex)
{
return false;
}
return true;
}
#region 获取一个新的文件完整路径
///
/// 获取一个新的文件完整路径
///
/// 文件后缀
/// 文件名称,为空时用Guid
///
public static string CreateNewFilePath(FileSuffixType fileSuffix, string fileName = "")
{
return HttpExtend.MapFile((string.IsNullOrWhiteSpace(fileName) ? Guid.NewGuid().ToString("N") : fileName) + "." + fileSuffix.ToString(), $"Cache\\{GetDirNameByFileSuffixType(fileSuffix)}");
}
///
/// 获取一个新的文件完整路径
///
/// 不带点的后缀名(例如:jpg)
/// 保存在缓存目录下的子目录名称
///
public static string CreateNewFilePath(string fileSuffix, string chipDirName)
{
return HttpExtend.MapFile(Guid.NewGuid().ToString("N") + "." + fileSuffix, $"Cache\\{chipDirName}");
}
///
/// 后缀获取目录名
///
///
///
private static string GetDirNameByFileSuffixType(FileSuffixType fileSuffixType)
{
switch (fileSuffixType)
{
case FileSuffixType.jpg:
case FileSuffixType.png:
case FileSuffixType.gif:
case FileSuffixType.ico:
return "Image";
case FileSuffixType.mp4:
return "Video";
case FileSuffixType.txt:
case FileSuffixType.doc:
return "Doc";
case FileSuffixType.rar:
return "Zip";
case FileSuffixType.silk:
case FileSuffixType.mp3:
return "Audio";
default:
return "Other";
}
}
#endregion
//[System.Runtime.InteropServices.DllImport("USER32.DLL")]
//public static extern bool SetForegroundWindow(IntPtr hWnd);
//[System.Runtime.InteropServices.DllImport("USER32.dll")]
//private static extern int ShowWindow(IntPtr hwnd, uint nCmdShow);
//public static void ActivateWindow()
//{
// ////if (DateTime.Now.Hour == 4)
// //{
// List processes = new List();
// var process = Process.GetProcessesByName("WECHAT").ToList();
// process.Add(Process.GetCurrentProcess());
// processes.AddRange(process);
// var process2 = Process.GetProcessesByName("WXWORK").ToList();
// //process2.Add(Process.GetCurrentProcess());
// processes.AddRange(process2);
// Task.Factory.StartNew(() =>
// {
// foreach (var item in processes)
// {
// try
// {
// var hwnd = item.MainWindowHandle;
// ShowWindow(hwnd, 9);
// SetForegroundWindow(hwnd);
// }
// catch (Exception)
// {
// }
// Thread.Sleep(1000);
// }
// });
// //}
//}
#region 激活窗体
public struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
private static extern int GetWindowRect(IntPtr hwnd, out Rect lpRect);
[DllImport("user32.dll")]
private static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
[System.Runtime.InteropServices.DllImport("USER32.DLL")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("USER32.dll")]
private static extern int ShowWindow(IntPtr hwnd, uint nCmdShow);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr SetActiveWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "FindWindow")] //声明FindWindowAPI
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr FindWindowExA(IntPtr parentHandle, IntPtr childAfter, string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32")]
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
const int MOUSEEVENTF_MOVE = 0x0001; //移动鼠标
const int MOUSEEVENTF_LEFTDOWN = 0x0002; //模拟鼠标左键按下
const int MOUSEEVENTF_LEFTUP = 0x0004; //模拟鼠标左键抬起
const int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模拟鼠标右键按下
const int MOUSEEVENTF_RIGHTUP = 0x0010; //模拟鼠标右键抬起
const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; //模拟鼠标中键按下
const int MOUSEEVENTF_MIDDLEUP = 0x0040; //模拟鼠标中键抬起
const int MOUSEEVENTF_ABSOLUTE = 0x8000; //标示是否采用绝对坐标
private const int VM_NCLBUTTONDOWN = 0XA1;//定义鼠标左键按下
private const int HTCAPTION = 2;
///
/// 激活个人微信窗口
///
private static void ActivateWindow(String lpClassName, string lpWindowName)
{
try
{
//主窗口句柄
var handle = IntPtr.Zero;
var handleList = new List();
do
{
//查找窗口句柄并筛选
handle = FindWindowExA(IntPtr.Zero, handle, lpClassName, lpWindowName);
if (handle == IntPtr.Zero) break;
if (handleList.Contains(handle)) break;
handleList.Add(handle);
//开始通过win32激活
var showWindow = ShowWindow(handle, 9);
Thread.Sleep(500);
var setActiveWindow = SetActiveWindow(handle);
Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(1000, 3000));
var setForegroundWindow = SetForegroundWindow(handle);
Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(2000, 5000));
////找窗口的坐标
//Rect rect = new Rect();
//var getWindowRect = GetWindowRect(handle, out var lpRect);
////设置鼠标的位置
//var setCursorPos = SetCursorPos(lpRect.Left + new Random(Guid.NewGuid().GetHashCode()).Next(10, 30), lpRect.Top + new Random(Guid.NewGuid().GetHashCode()).Next(5, 12));
var release = ReleaseCapture();
int x = new Random(Guid.NewGuid().GetHashCode()).Next(10, 30);
int y = new Random(Guid.NewGuid().GetHashCode()).Next(5, 12);
var one = SendMessage(handle, 0x201, IntPtr.Zero, new IntPtr(x + (y << 16)));
Thread.Sleep(300);
var two = SendMessage(handle, 0x202, IntPtr.Zero, new IntPtr(x + (y << 16)));
//LogHelper.GetSingleObj().Info("激活", $"激活窗口 => showWindow:{showWindow};setActiveWindow={setActiveWindow};setForegroundWindow={setForegroundWindow};getWindowRect={getWindowRect};{JsonConvert.SerializeObject(lpRect)};setCursorPos={setCursorPos};release={release};mouse={sendMessage}");
LogHelper.GetSingleObj().Info("激活", $"激活窗口 => showWindow:{showWindow};setActiveWindow={setActiveWindow};setForegroundWindow={setForegroundWindow};release={release};x={x};y={y};one={one};two={two}");
Thread.Sleep(2000);
} while (true);
}
catch (Exception e)
{
Console.WriteLine($"ActivateWindow Error:{e.Message}\r\nParams:lpClassName={lpClassName} lpWindowName={lpWindowName}");
}
}
///
/// 激活windows窗口
///
public static void ActivateWindow()
{
Task.Factory.StartNew(() =>
{
//激活个人微信
ActivateWindow("WeChatMainWndForPC", "微信");
Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(4000, 10000));
//激活企业微信
ActivateWindow("WeWorkWindow", "企业微信");
});
}
#endregion
private static string Device = string.Empty;
///
/// 获取设备信息
///
///
internal static string GetDevice()
{
if (!string.IsNullOrWhiteSpace(Device)) return Device;
var info = string.Empty;
try
{
info = FingerPrint.Value(); //+ Dns.GetHostName();
}
catch (Exception)
{ }
if (string.IsNullOrWhiteSpace(info))
info = Environment.CurrentDirectory;
return HttpExtend.GetMD5String(info);
}
private static Version _version;
///
/// 当前版本
///
public static Version CurVersion
{
get
{
if (_version == null)
{
try
{
_version = new Version(UpdateClient.GetVersionName());
}
catch (Exception ex)
{
_version = Version.Parse("0.0.0.0");
}
}
return _version;
}
}
///
/// xml处理
///
///
///
public static string XMLDispose(string xml)
{
try
{
var xmlCopy = xml;
var reg = Regex.Match(xmlCopy, @"(?<标题>[\w\W]+?)");
if (reg.Success)
{
xmlCopy = xmlCopy.Replace($@"{reg.Groups["标题"].Value}", $@"{reg.Groups["标题"].Value.XMLReplace()}");
}
reg = Regex.Match(xmlCopy, @"(?<介绍>[\w\W]+?)");
if (reg.Success)
xmlCopy = xmlCopy.Replace($@"{reg.Groups["介绍"].Value}", $@"{reg.Groups["介绍"].Value.XMLReplace()}");
reg = Regex.Match(xmlCopy, @"(?<链接>[\w\W]+?)");
if (reg.Success)
xmlCopy = xmlCopy.Replace($@"{reg.Groups["链接"].Value}", $@"{reg.Groups["链接"].Value.XMLReplace()}");
reg = Regex.Match(xmlCopy, @"(?<图片链接>[\w\W]+?)");
if (reg.Success)
xmlCopy = xmlCopy.Replace($@"{reg.Groups["图片链接"].Value}", $@"{reg.Groups["图片链接"].Value.XMLReplace()}");
return xmlCopy;
}
catch (Exception ex)
{ }
return xml;
}
public static string XMLReplace(this string str, bool addCdata = true)
{
var _str = string.Empty;
var reg = Regex.Match(str, @"[\w\W]+?)\]\]");
_str = reg.Success ? reg.Groups["内容"].Value : str;
return addCdata ? $"" : _str;
}
///
/// 删除目录
///
public static void DeleteDir(string path)
{
if (Directory.Exists(path))
{
try
{
DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
try
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
//else if (!IsOnlyDirectory)
// File.Delete(i.FullName); //删除指定文件
}
catch (Exception ex)
{ }
}
}
catch
{ }
}
}
///
/// 设置缓存(辅助输入)
///
///
///
///
///
public static bool SetCache(string key, object value, int secondes = 60)
{
try
{
Cache cache = HttpRuntime.Cache;
//查找 md5 的缓存,不存在则返回null
object item = cache[key];
if (item == null)
cache.Insert(key, value, null, DateTime.Now.AddSeconds(secondes), System.Web.Caching.Cache.NoSlidingExpiration);
return true;
}
catch (Exception ex)
{ }
return false;
}
///
/// 缓存是否存在
///
///
///
///
///
public static T GetCache(string key) where T : class
{
try
{
Cache cache = HttpRuntime.Cache;
object item = cache[key];
if (item != null)
return item as T;
}
catch (Exception)
{
}
return default(T);
}
///
/// 删除缓存
///
///
///
public static bool RemoveCache(string key)
{
try
{
Cache cache = HttpRuntime.Cache;
cache.Remove(key);
return true;
}
catch (Exception e)
{
return false;
}
}
///
/// 缓存是否存在
///
///
///
///
///
public static bool GetCache(string text)
{
try
{
var MD5 = GetMD5($"{text}");
Cache cache = HttpRuntime.Cache;
object item = cache[MD5];
return item != null ? true : false;
}
catch (Exception)
{
}
return false;
}
///
/// 设置缓存(辅助输入)
///
///
///
///
///
public static bool SetCache(string text, int secondes = 60)
{
try
{
var MD5 = GetMD5($"{text}");
Cache cache = HttpRuntime.Cache;
//查找 md5 的缓存,不存在则返回null
object item = cache[MD5];
if (item == null)
cache.Insert(MD5, 1, null, DateTime.Now.AddSeconds(secondes), System.Web.Caching.Cache.NoSlidingExpiration);
return true;
}
catch (Exception ex)
{ }
return false;
}
///
/// 缓存是否存在
///
///
///
///
///
public static bool GetCache(string robotname, string username, string text)
{
try
{
var MD5 = GetMD5(ToAllTrim($"{robotname}{username}{text}"));
Cache cache = HttpRuntime.Cache;
object item = cache[MD5];
return item != null ? true : false;
}
catch (Exception)
{
}
return false;
}
///
/// 设置缓存(辅助输入)
///
///
///
///
///
public static bool SetCache(string robotname, string username, string text, int seconds = 70)
{
try
{
var MD5 = GetMD5(ToAllTrim($"{robotname}{username}{text}"));
Cache cache = HttpRuntime.Cache;
//查找 md5 的缓存,不存在则返回null
object item = cache[MD5];
if (item == null)
cache.Insert(MD5, 1, null, DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration);
return true;
}
catch (Exception ex)
{ }
return false;
}
///
/// 删除所有的不可见
///
///
///
public static string ToAllTrim(string str)
{
return Regex.Replace(str, @"\s", "");
}
[DllImport("Kernel32.dll")]
//BOOL ReadProcessMemory(
// HANDLE hProcess,
// LPCVOID lpBaseAddress,
// LPVOID lpBuffer,
// SIZE_T nSize,
// SIZE_T* lpNumberOfBytesRead
//);
public static extern int ReadProcessMemory(
IntPtr hProcess, //正在读取内存的进程句柄。句柄必须具有PROCESS_VM_READ访问权限。
IntPtr lpBaseAddress, //指向要从中读取的指定进程中的基址的指针。在发生任何数据传输之前,系统会验证基本地址和指定大小的内存中的所有数据是否都可以进行读访问,如果无法访问,则该函数将失败。
byte[] lpBuffer, //指向缓冲区的指针,该缓冲区从指定进程的地址空间接收内容。
int nSize, //要从指定进程读取的字节数。
int lpNumberOfBytesRead //指向变量的指针,该变量接收传输到指定缓冲区的字节数。如果lpNumberOfBytesRead为NULL,则忽略该参数。
);
public static string GetString(IntPtr hProcess, IntPtr lpBaseAddress, int nSize = 100)
{
byte[] data = new byte[nSize];
if (ReadProcessMemory(hProcess, lpBaseAddress, data, nSize, 0) == 0)
{
//读取内存失败!
return "";
}
var result = string.Empty;
var uin = BitConverter.ToUInt32(data, 0);//将字节数组内容再转成int32类型
return uin.ToString();
//var TempString = Encoding.ASCII.GetString(data);
//// \0
//foreach (char item in TempString)
//{
// if (item == '\0')
// {
// break;
// }
// result += item.ToString();
//}
//return result;
}
///
/// 是否公众号
///
///
///
public static bool IsGzh(this string wxid, bool isgzh = false)
{
if (isgzh && wxid.StartsWith("gh_"))
return false;
return (wxid.StartsWith("gh_") || wxid == "newsapp" || wxid == "weixin" || wxid == "notifymessage");
}
///
/// 文件MD5校验
///
///
///
public static string GetMD5Hash(string pathName)
{
string strResult = "";
string strHashData = "";
byte[] arrbytHashValue;
FileStream oFileStream = null;
MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
try
{
oFileStream = new FileStream(pathName, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);//计算指定Stream 对象的哈希值
oFileStream.Close();
//由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
strHashData = BitConverter.ToString(arrbytHashValue);
//替换-
strHashData = strHashData.Replace("-", "");
strResult = strHashData;
}
catch (System.Exception ex)
{ }
return strResult;
}
///
/// MD5字符串加密
///
///
/// 加密后字符串
public static string GetMD5(string txt)
{
using (MD5 mi = MD5.Create())
{
byte[] buffer = Encoding.Default.GetBytes(txt);
//开始加密
byte[] newBuffer = mi.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newBuffer.Length; i++)
{
sb.Append(newBuffer[i].ToString("x2"));
}
return sb.ToString();
}
}
public static string StringMid(string Src, string Left, string Right)
{
string lRusult = string.Empty;
if (Src != string.Empty)
{
int dwLeft = Src.IndexOf(Left);
if (dwLeft != -1)
{
dwLeft += Left.Length;
int dwRight = Src.IndexOf(Right, dwLeft);
if (dwRight != -1)
{
lRusult = Src.Substring(dwLeft, dwRight - dwLeft);
}
}
}
return lRusult;
}
public static string CacheFilePath(string mWxid, string uWxid, string fName, string uName, string uExt)
{
string filePath = Directory.GetCurrentDirectory() + "\\Accounts\\" + mWxid + "\\" + fName + "\\" + uWxid;
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
SetFileRole(filePath);
filePath += "\\" + uName + "." + uExt;
return filePath;
}
///
/// 设置文件夹权限,处理为Everyone所有权限
///
/// 文件夹路径
public static void SetFileRole(string foldPath)
{
try
{
Thread.Sleep(500);
DirectorySecurity fsec = new DirectorySecurity();
//添加Everyone用户组的访问权限规则 完全控制权限
fsec.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
//添加Users用户组的访问权限规则 完全控制权限
fsec.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
//添加Authenticated Users用户组的访问权限规则 完全控制权限
fsec.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.FullControl, AccessControlType.Allow));
Directory.SetAccessControl(foldPath, fsec);
Thread.Sleep(500);
}
catch (Exception)
{ }
}
/**
* 判断是否是xml结构
*/
public static bool isXML(string value)
{
try
{
//XmlDocument xdoc = new XmlDocument();
//xdoc.LoadXml(value);
//return true;
//上面的这里有些情况下不准
var reg = Regex.IsMatch(value.Trim(), @"(.*0[\w\W]*1Window wechat)");
return reg;
}
catch (Exception ex)
{
return false;
}
}
///
/// 文件转换成Base64字符串
///
/// 文件绝对路径
///
public static String FileToBase64(string fileName)
{
string strRet = "";
try
{
FileStream fs = new FileStream(fileName, FileMode.Open);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
strRet = Convert.ToBase64String(bt);
fs.Close();
}
catch (Exception ex)
{
strRet = null;
}
return strRet;
}
///
/// Base64字符串转换成文件
///
/// base64字符串
/// 保存文件的绝对路径
///
public static bool Base64ToFileAndSave(string strInput, string fileName)
{
bool bTrue = false;
try
{
byte[] buffer = Convert.FromBase64String(strInput);
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
bTrue = true;
}
catch (Exception ex)
{ }
return bTrue;
}
#region 判断一个字符串是否是base64字符串
///
/// 是否base64字符串
///
/// 要判断的字符串
///
public static bool IsBase64(this string base64Str)
{
byte[] bytes = null;
return IsBase64(base64Str, out bytes);
}
///
/// 是否base64字符串
///
/// 要判断的字符串
/// 字符串转换成的字节数组
///
private static bool IsBase64(string base64Str, out byte[] bytes)
{
//string strRegex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
bytes = null;
if (string.IsNullOrEmpty(base64Str))
return false;
else
{
if (base64Str.Contains(","))
base64Str = base64Str.Split(',')[1];
if (base64Str.Length % 4 != 0)
return false;
if (base64Str.Any(c => !base64CodeArray.Contains(c)))
return false;
}
try
{
bytes = Convert.FromBase64String(base64Str);
return true;
}
catch (FormatException)
{
return false;
}
}
private static char[] base64CodeArray = new char[]
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '='
};
#endregion
#region Base64 与 Image互转
public static string ConvertImageToBase64(Image file)
{
using (MemoryStream memoryStream = new MemoryStream())
{
file.Save(memoryStream, file.RawFormat);
byte[] imageBytes = memoryStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
public static Bitmap ConvertBase64ToImage(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
ms.Write(imageBytes, 0, imageBytes.Length);
using (Image mImage = Image.FromStream(ms, true))
{
return new Bitmap(mImage);
}
}
}
#endregion
#region 获取图片后缀
///
/// 获取图片后缀
///
///
///
public static string GetImageExt(Image image)
{
string imageExt = "jpg";
var RawFormatGuid = image.RawFormat.Guid;
if (ImageFormat.Png.Guid == RawFormatGuid)
{
imageExt = "png";
}
if (ImageFormat.Jpeg.Guid == RawFormatGuid)
{
imageExt = "jpg";
}
if (ImageFormat.Bmp.Guid == RawFormatGuid)
{
imageExt = "bmp";
}
if (ImageFormat.Gif.Guid == RawFormatGuid)
{
imageExt = "gif";
}
if (ImageFormat.Icon.Guid == RawFormatGuid)
{
imageExt = "icon";
}
return imageExt;
}
#endregion
#region 压缩图片
///
/// 壓縮圖片 ///
/// 圖片流
/// 壓縮質量0-100之間 數值越大質量越高
///
public static Bitmap CompressionImage(Stream fileStream, long quality)
{
try
{
using (Image img = Image.FromStream(fileStream))
{
//using (Bitmap bitmap = new Bitmap(img))
Bitmap bitmap = new Bitmap(img);
{
ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
myEncoderParameters.Param[0] = myEncoderParameter;
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, CodecInfo, myEncoderParameters);
myEncoderParameters.Dispose();
myEncoderParameter.Dispose();
return bitmap;
//return ms.ToArray();
}
}
}
}
catch (Exception)
{ return null; }
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{ return codec; }
}
return null;
}
#endregion
public static bool AppConfig_ExistItem(string keyName)
{
//判断配置文件中是否存在键为keyName的项
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == keyName)
{
//存在
return true;
}
}
return false;
}
public static string AppConfig_Get(string keyName)
{
//返回配置文件中键为keyName的项的值
return ConfigurationManager.AppSettings[keyName];
}
public static void AppConfig_Set(string key, string value)
{
var cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings[key].Value = value;
cfa.Save();
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}
public static void AppConfig_Add(string key, string value)
{
var cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings.Add(key, value);
cfa.Save();
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}
public static List GetProcesses()
{
try
{
var wmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var sss = Process.GetProcesses();
foreach (var s in sss)
{
//var dd = JsonConvert.SerializeObject(s);
}
var query = from p in Process.GetProcesses()
join mo in results.Cast()
on p.Id equals (int)(uint)mo["ProcessId"]
select new MyProcesses()
{
Process = p,
Path = (string)mo["ExecutablePath"],
CommandLine = (string)mo["CommandLine"],
MainWindowHandle = (IntPtr)mo["MainWindowHandle"],
};
return query.ToList();
}
}
catch (Exception ex)
{ }
return null;
}
public class MyProcesses
{
public Process Process { get; set; }
public string Path { get; set; }
public string CommandLine { get; set; }
public IntPtr MainWindowHandle { get; set; }
}
}
}