【分享】自己写的一些工作中常用到的扩展方法

NqIceCoffee 2010-12-03 10:07:48
加精
对于string的一些扩展

public static bool IsEmpty(this string input)
{
if (input == null || input.Trim().Length == 0)
return true;
return false;
}

public static int Length(this string input)
{
if (input.IsEmpty())
return 0;
int n = 0;
foreach (char c in input)
{
if ((int)c > 256)
n += 2;
else
n++;
}
return n;
}

public static string Interception(this string input, int length)
{
return input.Interception(0, length);
}

public static string Interception(this string input, int startIndex, int length)
{
if (input.IsEmpty()) return string.Empty;
int len = input.Length;
if (startIndex >= len) return string.Empty;

bool flag = false;
int i = startIndex, j = 0;
for (; i < len; i++)
{
if (j >= length)
{
flag = true;
break;
}

if ((int)input[i] > 256)
j += 2;
else
j++;
}

string returnValue = input.Substring(startIndex, i - startIndex);
if (flag)
returnValue += "...";
return returnValue;
}

public static string AppPath(this string input)
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, input);
}

public static string MD5(this string input)
{
string returnValue = string.Empty;
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] resultBytes = md5.ComputeHash(inputBytes);
foreach (byte b in resultBytes)
returnValue += b.ToString("X").PadLeft(2, '0');
md5.Clear();
return returnValue;
}

/// <summary>
/// RijndaelManaged加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Encrypt(this string input)
{
if (input.IsEmpty())
return string.Empty;
return BaseEncrypt.Encrypt(input);
}

/// <summary>
/// 解密RijndaelManaged加密字符串
/// </summary>
/// <param name="input"></param>
/// <param name="originalText">解密后的明文字符串</param>
/// <returns></returns>
public static string Decrypt(this string input)
{
if (input.IsEmpty())
return string.Empty;
try
{
return BaseEncrypt.Decrypt(input);
}
catch { }
return string.Empty;
}

/// <summary>
/// 带时间戳的RijndaelManaged加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncyptWithTime(this string input)
{
if (input.IsEmpty())
return string.Empty;
int l = input.Length;
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Random rnd = new Random();
int P = rnd.Next(l);

input = input.Insert(P, time);
input = input.Encrypt();
input += string.Format("^{0}", P);
return input.Encrypt();
}

/// <summary>
/// 解密带时间戳的RijndaelManaged的加密串
/// </summary>
/// <param name="input"></param>
/// <param name="originalText">解密后的明文字符串</param>
/// <param name="time">时间戳</param>
/// <returns></returns>
public static bool TryDecryptWithTime(this string input, out string text, out DateTime time)
{
text = string.Empty;
time = DateTime.MinValue;

if (!(text = input.Decrypt()).IsEmpty())
{
int position = text.LastIndexOf('^');
if (position != -1)
{
int P = text.Substring(position + 1).ParseTo<int>();
if (P > 0)
{
text = text.Substring(0, position);
if (!(text = text.Decrypt()).IsEmpty())
{
time = text.Substring(P, 19).ParseTo<DateTime>();
text = text.Substring(0, P) + text.Substring(P + 19);
return true;
}
}
}
}

return false;
}


RijndaelManaged的加密用到的一个静态类:

public static class BaseEncrypt
{
private static byte[] iv = null;
private static byte[] key = null;
private static RijndaelManaged rm = new RijndaelManaged();

static BaseEncrypt()
{
string str_iv = ConfigurationManager.AppSettings["sys_EncryptIV"];
string str_key = ConfigurationManager.AppSettings["sys_EncryptKey"];

if (str_iv.Length() != 16)
str_iv = "&^q)@Mbl%s!2~8d#";

if (str_key.Length() != 32)
str_key = ")(*jJ6%y$^7s%#rap#sm&%$;j/a'1s]|";

iv = Encoding.ASCII.GetBytes(str_iv);
key = Encoding.ASCII.GetBytes(str_key);
}

public static string Encrypt(string input)
{
byte[] inputArr = Encoding.Default.GetBytes(input);

rm.IV = iv;
rm.Key = key;

ICryptoTransform ict = rm.CreateEncryptor();
MemoryStream memory = new MemoryStream();
CryptoStream crypt = new CryptoStream(memory, ict, CryptoStreamMode.Write);
crypt.Write(inputArr, 0, inputArr.Length);
crypt.FlushFinalBlock();

byte[] _Result = memory.ToArray();
memory.Close();

return Convert.ToBase64String(_Result);
}

public static string Decrypt(string input)
{
byte[] _Input = Convert.FromBase64String(input);
MemoryStream _Memory = new MemoryStream(_Input, 0, _Input.Length);

rm.IV = iv;
rm.Key = key;

ICryptoTransform ict = rm.CreateDecryptor();
CryptoStream crypt = new CryptoStream(_Memory, ict, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(crypt);

return sr.ReadToEnd();
}
}



抛砖引玉,欢迎大家补充交流
...全文
4184 218 打赏 收藏 转发到动态 举报
写回复
用AI写文章
218 条回复
切换为时间正序
请发表友善的回复…
发表回复
木子亘 2011-05-31
  • 打赏
  • 举报
回复
我只能说谢谢楼主了!
hj3424361 2011-04-12
  • 打赏
  • 举报
回复
来个简单的



/// <summary>
/// 截取小数位
/// </summary>
/// <param name="value"></param>
/// <param name="count"></param>
/// <returns></returns>
public static float CutNum(double value,int count)
{
return float.Parse(Math.Round((value), count).ToString());
}

飞啊子 2011-02-18
  • 打赏
  • 举报
回复
方法名 是 ToInt;
飞啊子 2011-02-18
  • 打赏
  • 举报
回复
[Quote=引用 35 楼 wptad 的回复:]
接下来是与int相关的操作:

C# code



public static bool IsInt(this string s)
{
int i;
return int.TryParse(s, out i);
}

public static int ToInt(this string s)
{
……
[/Quote]


还不如这样写。
public static bool IsInt(this string s,out int i)
{
return int.TryParse(s, out i);
}
辛鹤 2011-01-13
  • 打赏
  • 举报
回复
想到会爆冷
IT_lujianlin 2011-01-09
  • 打赏
  • 举报
回复
感觉好乱呀
..........
werdongyu 2010-12-14
  • 打赏
  • 举报
回复
嗯 不错 学习了
gdk123 2010-12-14
  • 打赏
  • 举报
回复
顶帖是一种美德
truecoffeefox 2010-12-14
  • 打赏
  • 举报
回复
全角半角字符转换问题,做新闻发布系统时比较实用,有时标题标点字母如果是全角实在难看这样给过滤个

namespace Coffeefox.Tools
{
/// <summary>
/// 使用:using即可
/// </summary>
public static class CaseChange
{
/// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input">任意字符串</param>
/// <returns>全角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public static string ToSBC(this string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
return new string(c);
}
/// <summary> 转半角的函数(DBC case) </summary>
/// <param name="input">任意字符串</param>
/// <returns>半角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public static string ToDBC(this string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
}
}
truecoffeefox 2010-12-14
  • 打赏
  • 举报
回复
一个比较好的随机码,RNGCryptoServiceProvider实现比单纯random要好的多
//产生随机数种子
private static int GetNewSeed()
{
byte[] rndBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(rndBytes);
return BitConverter.ToInt32(rndBytes, 0);
}

// 序列生成函数,需要字典和长度
private static string BuildRndCode(string CodeDictionary, int strLen)
{
System.Random RandomObj = new System.Random(GetNewSeed());
string buildRndCodeReturn = null;
for (int i = 0; i < strLen; i++)
{
buildRndCodeReturn += CodeDictionary.Substring(RandomObj.Next(0, CodeDictionary.Length - 1), 1);
}
return buildRndCodeReturn;
}
只给出通用模块,具体调用自己写吧,那些无所谓的东西
truecoffeefox 2010-12-14
  • 打赏
  • 举报
回复
参考了部分网上的例子,例子里空文件夹被忽略了
我觉得应该保持源状态,所以空文件夹保留

using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace Coffeefox.Tools.CompressFile
{
/// <summary>
/// 解压类
/// </summary>
public static partial class ZIPCompress
{
public static void UnCompress(string compressedFile)
{
UnCompress(compressedFile, compressedFile);
}

/// <summary>
/// 解压缩文件
/// </summary>
/// <param name="compressedFile">待解压缩的文件路径</param>
/// <param name="unCompressTo">解压缩到指定目录</param>
public static void UnCompress(string compressedFile, string unCompressTo)
{
if (string.IsNullOrEmpty(unCompressTo)) { unCompressTo = compressedFile; }

if (!File.Exists(compressedFile) || !Path.GetExtension(compressedFile).ToLower().Equals(".zip")) { throw new IOException("待解压文件不存在或不为zip文件"); }

if (compressedFile.Equals(unCompressTo))
{
unCompressTo = Path.GetDirectoryName(compressedFile); ;
}

if (!Directory.Exists(unCompressTo)) { Directory.CreateDirectory(unCompressTo); }

if (!unCompressTo.EndsWith("\\")) { unCompressTo += "\\"; }

ZipInputStream s = new ZipInputStream(File.OpenRead(compressedFile));
//if (!string.IsNullOrEmpty(password))
//{
// s.Password = password;
//}
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = unCompressTo;//Path.GetDirectoryName();
string fileName = Path.GetFileName(theEntry.Name);
//生成解压目录
Directory.CreateDirectory(directoryName);
if (fileName != String.Empty)
{
//解压文件到指定的目录
directoryName = Path.GetDirectoryName(unCompressTo + theEntry.Name);
//建立下面的目录和子目录
Directory.CreateDirectory(directoryName);
FileStream streamWriter = File.Create(unCompressTo + theEntry.Name);
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();
}
}
}
NqIceCoffee 2010-12-14
  • 打赏
  • 举报
回复
楼上的代码不错,很实用~~

感谢分享
truecoffeefox 2010-12-14
  • 打赏
  • 举报
回复
有些环境可能不能读注册表或者安装winrar
就得用sharpzip了

using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;

namespace Coffeefox.Tools.CompressFile
{
/// <summary>
/// 压缩文件
/// </summary>
public static partial class ZIPCompress
{
/// <summary>
/// 压缩单个文件,以源文件命名保存于源文件同级目录下
/// </summary>
/// <param name="fileToCompress">源文件完整路径</param>
public static void CompressFile(string fileToCompress)
{
CompressFile(fileToCompress, fileToCompress);
}
/// <summary>
/// 压缩单个文件,保存于指定路径/指定路径+文件名
/// </summary>
/// <param name="fileToCompress">源文件完整路径</param>
/// <param name="compressedFilePath">目标路径+目标文件名,不指定文件名以目标路径命名</param>
public static void CompressFile(string fileToCompress, string compressedFilePath)
{
if (!File.Exists(fileToCompress)) { throw new System.IO.FileNotFoundException("源文件不存在!"); }
if (fileToCompress.EndsWith("\\")) { fileToCompress = fileToCompress.Substring(0, fileToCompress.Length - 1); }
if (compressedFilePath.EndsWith("\\")) { compressedFilePath = compressedFilePath.Substring(0, compressedFilePath.Length - 1); }

//源与目的相同根据源生成目的
if (fileToCompress.Equals(compressedFilePath)) { compressedFilePath = Path.Combine(Path.GetDirectoryName(fileToCompress), Path.GetFileNameWithoutExtension(fileToCompress)); }
else
{
if (string.IsNullOrEmpty(Path.GetExtension(compressedFilePath)))
//目的是路径,与源文件名拼接路径拼接
{ compressedFilePath = Path.Combine(compressedFilePath, Path.GetFileNameWithoutExtension(fileToCompress)); }
}
//加后缀名
if (string.IsNullOrEmpty(Path.GetExtension(compressedFilePath)) || !Path.GetExtension(compressedFilePath).ToLower().Equals(".zip"))
{ compressedFilePath += ".zip"; }
//保存的路径不存在就创建路径
string saveFileDirectory = Path.GetDirectoryName(compressedFilePath);
if (!Directory.Exists(saveFileDirectory)) { Directory.CreateDirectory(saveFileDirectory); }
//压缩
using (FileStream fs = File.OpenRead(fileToCompress))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
using (FileStream ZipFile = File.Create(compressedFilePath))
{
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
{
string fileName = fileToCompress.Substring(fileToCompress.LastIndexOf("\\") + 1);
ZipEntry ZipEntry = new ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(6);
ZipStream.Write(buffer, 0, buffer.Length);
ZipStream.Finish();
ZipStream.Close();
}
}
}
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="pathToCompress">源文件夹</param>
/// <param name="fileFilter">指定压缩的文件类型</param>
/// <returns></returns>
public static bool CompressFolder(string pathToCompress, string fileFilter)
{
return CompressFolder(pathToCompress, pathToCompress, fileFilter);
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="pathToCompress">源文件夹</param>
/// <param name="compressedFileFullName">目标文件夹或者文件名,不可以是源的子目录</param>
/// <param name="fileFilter">指定压缩的文件类型</param>
/// <returns></returns>
public static bool CompressFolder(string pathToCompress, string compressedFileFullName, string fileFilter)
{
if (!Directory.Exists(pathToCompress)) { throw new IOException("源文件夹不存在"); }
if (pathToCompress.EndsWith("\\")) { pathToCompress = pathToCompress.Substring(0, pathToCompress.Length - 1); }
if (compressedFileFullName.EndsWith("\\")) { compressedFileFullName = compressedFileFullName.Substring(0, compressedFileFullName.Length - 1); }
//目标是源的子目录,递归会出错,应排除
if (compressedFileFullName.Length > pathToCompress.Length && compressedFileFullName.Replace(pathToCompress, "").StartsWith("\\")) { throw new IOException("目标不能为源目录的子级目录"); }

//源与目的相同,目的为以源文件夹命名,与源文件夹同级
if (pathToCompress.Equals(compressedFileFullName)) { compressedFileFullName = Path.Combine(Path.GetDirectoryName(pathToCompress), Path.GetFileNameWithoutExtension(pathToCompress)); }
else
{
if (string.IsNullOrEmpty(Path.GetExtension(compressedFileFullName)))//目标是路径
{
compressedFileFullName = Path.Combine(compressedFileFullName, Path.GetFileNameWithoutExtension(pathToCompress));
}
}
//更正目标后缀名
if (string.IsNullOrEmpty(Path.GetExtension(compressedFileFullName)) || !Path.GetExtension(compressedFileFullName).Equals(".zip")) { compressedFileFullName += ".zip"; }
//文件过滤
if (string.IsNullOrEmpty(fileFilter)) { fileFilter = "*.*"; }
//保存的路径不存在就创建路径
string saveFileDirectory = Path.GetDirectoryName(compressedFileFullName);
if (!Directory.Exists(saveFileDirectory)) { Directory.CreateDirectory(saveFileDirectory); }

if (!pathToCompress.EndsWith("\\")) { pathToCompress += "\\"; }
try
{
Crc32 crc = new Crc32();
ZipOutputStream zipedStream = new ZipOutputStream(File.Create(compressedFileFullName));
zipedStream.SetLevel(6); // 0 - store only to 9 - means best compression
DirectoryInfo directoryToCompress = new DirectoryInfo(pathToCompress);
FileInfo[] filesInDirectory = directoryToCompress.GetFiles(fileFilter);
string basePath = pathToCompress.Trim();
//压缩这个目录下的所有文件
writeStream(ref zipedStream, filesInDirectory, crc, basePath);
//压缩这个目录下子目录及其文件
TraversalSubDirectory(directoryToCompress, ref zipedStream, crc, basePath, fileFilter);
zipedStream.Finish();
zipedStream.Close();
}
catch
{
return false;
}
return true;
}

/// <summary>
/// 递归遍历子文件夹极其文件
/// </summary>
/// <param name="directoryToCompress"></param>
/// <param name="zipedStream"></param>
/// <param name="crc"></param>
/// <param name="basePath"></param>
/// <param name="fileFilter"></param>
private static void TraversalSubDirectory(DirectoryInfo directoryToCompress, ref ZipOutputStream zipedStream, Crc32 crc, string basePath, string fileFilter)
{
DirectoryInfo[] dirs = directoryToCompress.GetDirectories("*");
//遍历目录下面的所有的子目录
foreach (DirectoryInfo dirNext in dirs)
{
//将该目录下的所有文件添加到 ZipOutputStream s 压缩流里面
FileInfo[] a = dirNext.GetFiles(fileFilter);
writeStream(ref zipedStream, a, crc, basePath);
//递归调用直到把所有的目录遍历完成
TraversalSubDirectory(dirNext, ref zipedStream, crc, basePath, fileFilter);
}
}
/// <summary>
/// 写入压缩文件
/// </summary>
/// <param name="s"></param>
/// <param name="a"></param>
/// <param name="crc"></param>
/// <param name="basePath"></param>
private static void writeStream(ref ZipOutputStream s, FileInfo[] a, Crc32 crc, string basePath)
{
foreach (FileInfo fi in a)
{
FileStream fs = fi.OpenRead();
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string file = fi.FullName;
file = file.Replace(basePath, "");
ZipEntry entry = new ZipEntry(file);
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);
}
}
}
}
truecoffeefox 2010-12-14
  • 打赏
  • 举报
回复
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Win32;

namespace Coffeefox.Tools.CompressFile
{
public static partial class RARCompress
{
/// <summary>
/// 解压缩
/// </summary>
/// <param name="rarFileFullPath">待压缩文件</param>
/// <param name="overwrite">true为覆盖已存同名文件,false为跳过</param>
public static void UnCompress(string rarFileFullPath, bool overwrite)
{
UnCompress(rarFileFullPath, rarFileFullPath, overwrite);
}
/// <summary>
/// 解压缩
/// </summary>
/// <param name="rarFileFullPath">待压缩文件</param>
/// <param name="unCompressPath">目的文件夹</param>
/// <param name="overwrite">true为覆盖已存同名文件,false为跳过</param>
public static void UnCompress(string rarFileFullPath, string unCompressPath, bool overwrite)
{
if (string.IsNullOrEmpty(unCompressPath)) { unCompressPath = rarFileFullPath; }
if (!rarFileFullPath.EndsWith(".rar") && !File.Exists(rarFileFullPath)) { throw new FileNotFoundException("源文件不存在"); }
//if (unCompressPath.EndsWith("\\")) { unCompressPath = unCompressPath.Substring(0, unCompressPath.Length - 1); }
//解压文件与目标相同-取出解压文件所在文件夹作为目标
if (rarFileFullPath.Equals(unCompressPath)) { unCompressPath = Path.GetDirectoryName(rarFileFullPath); }

if (!Directory.Exists(unCompressPath)) { Directory.CreateDirectory(unCompressPath); }

//解压缩
String rarObjStr;
RegistryKey rarRegKey;
Object rarObj;
StringBuilder commandInfo = new StringBuilder();
ProcessStartInfo processInfo;
Process process;

rarRegKey = Registry.ClassesRoot.OpenSubKey(@"WinRAR\Shell\Open\Command");
rarObj = rarRegKey.GetValue("");
rarObjStr = rarObj.ToString();
rarRegKey.Close();
rarObjStr = rarObjStr.Substring(1, rarObjStr.Length - 7);

commandInfo.Append(" x ");
if (overwrite) { commandInfo.Append(" -o+ "); }
else { commandInfo.Append(" -o- "); }
commandInfo.Append(rarFileFullPath);
commandInfo.Append(" ");
commandInfo.Append(unCompressPath);

processInfo = new ProcessStartInfo();
processInfo.FileName = rarObjStr;
processInfo.Arguments = commandInfo.ToString();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
process = new Process();
process.StartInfo = processInfo;
process.Start();
process.WaitForExit();
}
}
}

客户端上传文件自动给他压缩了,省的带个马什么的
truecoffeefox 2010-12-14
  • 打赏
  • 举报
回复
也不好光看不发,这个是winrar压缩和解压缩的,两个文件,分部类
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Win32;

namespace Coffeefox.Tools.CompressFile
{
/// <summary>
/// 压缩解压rar文档,兼容zip,服务器端需安装winrar
/// </summary>
public static partial class RARCompress
{
#region 覆盖压缩
/// <summary>
/// 压缩,覆盖同名目标文件,不分卷
/// 目标文件以源文件夹或源文件名命名,保存于源文件/文件夹的同级目录下
/// </summary>
/// <param name="toCompress">要压缩的文件夹或文件名,文件夹后可加通配符匹配某类文件,如D:\\*.xls表示D盘根目录下的xls文件。</param>
public static void Compress(string toCompress)
{
Compress(toCompress, toCompress, false, 0);
}
/// <summary>
/// 压缩,覆盖同名目标文件,不分卷
/// </summary>
/// <param name="toCompress">要压缩的文件夹或文件名,文件夹后可加通配符匹配某类文件,如D:\\*.xls表示D盘根目录下的xls文件。</param>
/// <param name="compressedFileFullPath">最终压缩文件的完整路径,不加rar后缀名则以最后一级文件夹命名</param>
public static void Compress(string toCompress, string compressedFileFullPath)
{
Compress(toCompress, compressedFileFullPath, false, 0);
}
#endregion

#region 追加压缩
/// <summary>
/// 追加压缩,不可分卷
/// 目标文件以源文件夹或源文件名命名,保存于源文件/文件夹的同级目录下
/// </summary>
/// <param name="toCompress">要压缩的文件夹或文件名,文件夹后可加通配符匹配某类文件,如D:\\*.xls表示D盘根目录下的xls文件。</param>
public static void CompressAdditional(string toCompress)
{
CompressAdditional(toCompress, toCompress);
}
/// <summary>
/// 追加压缩,不可分卷
/// </summary>
/// <param name="toCompress">要压缩的文件夹或文件名,文件夹后可加通配符匹配某类文件,如D:\\*.xls表示D盘根目录下的xls文件。</param>
/// <param name="compressedFileFullPath">最终压缩文件的完整路径,不加rar后缀名则以最后一级文件夹命名</param>
public static void CompressAdditional(string toCompress, string compressedFileFullPath)
{
Compress(toCompress, compressedFileFullPath, true, 0);
}
#endregion

#region 分卷压缩
/// <summary>
/// 分卷压缩,覆盖同名目标文件,无法追加
/// 目标文件以源文件夹或源文件名命名,保存于源文件/文件夹的同级目录下
/// </summary>
/// <param name="toCompress">要压缩的文件夹或文件名,文件夹后可加通配符匹配某类文件,如D:\\*.xls表示D盘根目录下的xls文件。</param>
/// <param name="sizeLimit">指定大小则按照大小分卷压缩,单位为M,0表示不分卷</param>
public static void Compress(string toCompress, int sizeLimit)
{
Compress(toCompress, toCompress, sizeLimit);
}
/// <summary>
/// 分卷压缩,覆盖同名目标文件,无法追加
/// </summary>
/// <param name="toCompress">要压缩的文件夹或文件名,文件夹后可加通配符匹配某类文件,如D:\\*.xls表示D盘根目录下的xls文件。</param>
/// <param name="compressedFileFullPath">最终压缩文件的完整路径,不加rar后缀名则以最后一级文件夹命名</param>
/// <param name="sizeLimit">指定大小则按照大小分卷压缩,单位为M,0表示不分卷</param>
public static void Compress(string toCompress, string compressedFileFullPath, int sizeLimit)
{
Compress(toCompress, compressedFileFullPath, false, sizeLimit);
}
#endregion

/// <summary>
/// 压缩
/// </summary>
/// <param name="toCompress">要压缩的文件夹或文件名,文件夹后可加通配符匹配某类文件,如D:\\*.xls表示D盘根目录下的xls文件。分卷压缩可在前-v[n]m</param>
/// <param name="compressedFileFullPath">最终压缩文件的完整路径</param>
/// <param name="superAddition">存在同名压缩文件时,true=追加,false=覆盖</param>
/// <param name="sizeLimit">指定大小则按照大小分卷压缩,单位为M,0表示不分卷</param>
private static void Compress(string toCompress, string compressedFileFullPath, bool superAddition, int sizeLimit)
{
//源与目的,如果为路径都将最后的反斜杠去掉
if (toCompress.EndsWith("\\")) { toCompress = toCompress.Substring(0, toCompress.Length - 1); }
if (compressedFileFullPath.EndsWith("\\")) { compressedFileFullPath = compressedFileFullPath.Substring(0, compressedFileFullPath.Length - 1); }

//源不存在--异常
bool toCompressDirectoryExists = Directory.Exists(toCompress);
bool toCompressFileExists = File.Exists(toCompress);
if (!toCompressDirectoryExists && !toCompressFileExists) { throw new FileNotFoundException("待压缩源路径或文件不存在"); }

string[] filesToDelete = new string[0];
//分卷压缩-删除可能存在的分卷
if (sizeLimit > 0)
{
string filename = Path.GetFileNameWithoutExtension(compressedFileFullPath);
//源与目的相同
if (toCompress.Equals(compressedFileFullPath)) { filesToDelete = Directory.GetFiles(Path.GetDirectoryName(toCompress), filename + ".part*.rar", SearchOption.TopDirectoryOnly); }
//源与目的不同
else { filesToDelete = Directory.GetFiles(Path.GetDirectoryName(compressedFileFullPath), filename + ".part*.rar", SearchOption.TopDirectoryOnly); }
}
//非分卷且目的存在并选择覆盖--删除原存压缩文件
else { if (!superAddition && toCompressFileExists) { filesToDelete = new string[1] { compressedFileFullPath }; } }
//执行删除
if (filesToDelete.Length > 0) { foreach (string s in filesToDelete) { File.Delete(s); } }

//源与目的相同
if (toCompress.Equals(compressedFileFullPath))
{
//源是文件,用源文件命名,与源文件同级目录保存
//源是目录,以源最后级目录名命名,源目录上级目录保存
compressedFileFullPath = Path.Combine(Path.GetDirectoryName(toCompress), Path.GetFileNameWithoutExtension(toCompress));
}
else
{
//目的是路径
//源是文件,用源文件命名,与源文件同级目录保存
//源是目录,以源最后级目录名命名,源目录上级目录保存
if (string.IsNullOrEmpty(Path.GetExtension(compressedFileFullPath)))
{
compressedFileFullPath = Path.Combine(compressedFileFullPath, Path.GetFileNameWithoutExtension(toCompress));
}
//目的是文件掠过
}
//添加.rar后缀名--文件名指定错误的,由此生成错误文件名.rar
if (string.IsNullOrEmpty(Path.GetExtension(compressedFileFullPath)) || !Path.GetExtension(compressedFileFullPath).ToLower().Equals(".rar"))
{ compressedFileFullPath += ".rar"; }

//保存的路径不存在就创建路径
string saveFileDirectory = Path.GetDirectoryName(compressedFileFullPath);
if (!Directory.Exists(saveFileDirectory)) { Directory.CreateDirectory(saveFileDirectory); }

String rarObjStr;
RegistryKey rarRegKey;
Object rarObj;
StringBuilder commandInfo = new StringBuilder();
ProcessStartInfo processInfo;
Process process;

rarRegKey = Registry.ClassesRoot.OpenSubKey(@"WinRAR\Shell\Open\Command");
rarObj = rarRegKey.GetValue("");
rarObjStr = rarObj.ToString();
rarRegKey.Close();
rarObjStr = rarObjStr.Substring(1, rarObjStr.Length - 7);

commandInfo.Append(" a ");//压缩
if (!File.Exists(toCompress))//非文件-处理所有子文件夹
{
commandInfo.Append(" -r ");
}
if (sizeLimit > 0)//分卷压缩
{
commandInfo.Append("-v");
commandInfo.Append(sizeLimit.ToString());
commandInfo.Append("m ");

}
commandInfo.Append(compressedFileFullPath);
commandInfo.Append(" ");
commandInfo.Append(toCompress);

processInfo = new ProcessStartInfo();
processInfo.FileName = rarObjStr;
processInfo.Arguments = commandInfo.ToString();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.WorkingDirectory = toCompress;
process = new Process();
process.StartInfo = processInfo;
process.Start();
process.WaitForExit();
}
}
}
挖梦的搬运工 2010-12-13
  • 打赏
  • 举报
回复
好贴。。学习了
DeathSteps 2010-12-13
  • 打赏
  • 举报
回复
lz 威武,发起这么好的讨论。果断力顶!!!!
jjyan005 2010-12-13
  • 打赏
  • 举报
回复
学习了收藏
IHandler 2010-12-13
  • 打赏
  • 举报
回复
有些方法没有处理字符串为null的情况
wtin008 2010-12-13
  • 打赏
  • 举报
回复
好东西,好帖子,收藏了,谢谢楼主及各位的分享
加载更多回复(198)

62,041

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧