常用工具方法

public class Utils
{
/// <summary>
/// JSON
/// </summary>
/// <param name="txt"></param>
/// <returns></returns>
public static Dictionary<string, object> Json2Obj(string txt)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(txt);
return json;
}

public static bool SerializeObject(string path, Object obj)
{
FileStream fs = null;
bool b = false;
try
{
fs = new FileStream(path, FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, obj);
b = true;
}
catch (Exception e)
{
b = false;
CLogger.WriteLog(ELogLevel.ERROR, e.Message);
}
finally
{
if (fs != null)
fs.Close();
}
return b;
}

public static Object DeserializeObject(string path)
{
if (!File.Exists(path))
return null;
Object obj = new Object();

FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
obj = bf.Deserialize(fs);
}
catch (Exception e)
{
CLogger.WriteLog(ELogLevel.ERROR, e.Message);
}
finally
{
if (fs != null)
fs.Close();
}
return obj;
}

[DllImport("shell32.dll")]
public static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, Int32 nShowCmd);

public static bool CheckUrl(string url)
{
return Regex.IsMatch(url, "http[s]*://.+");
}
public static String HtmlClearCode(String formattedMessage, bool nbSpace, bool newLine)
{
if (string.IsNullOrEmpty(formattedMessage))
return formattedMessage;

while (formattedMessage.IndexOf("<") >= 0)
{
int i = formattedMessage.IndexOf("<");
int j = formattedMessage.IndexOf(">");
if (j >= 0)
{
j = j - i + 1;
}
else
{
j = formattedMessage.Length - i;
}

if (j < 0)
{
j = 0;
}

formattedMessage = formattedMessage.Remove(i, j);
}

//space
if (nbSpace)
{
formattedMessage = formattedMessage.Replace("&nbsp;", " ");
}

//br
if (newLine)
{
formattedMessage = formattedMessage.Replace("<br>", "");
}

return formattedMessage;
}

private static Random rand = new Random();

public static int NextInt(int maxInt)
{
return rand.Next(maxInt);
}



posted on 2011-12-27 10:57  risan  阅读(212)  评论(0编辑  收藏  举报