1. 检查同一位置的应用程序是否已经运行
[csharp toolbar=”false”]
private static bool GetRunningProcessByProcessFullName(out Process runningProcess)
{
bool returnValue = false;
runningProcess = null;
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
string assemblyName = Assembly.GetExecutingAssembly().Location;
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (process.MainModule.FileName == assemblyName)
{
runningProcess = process;
returnValue = true;
break;
}
}
}
return returnValue;
}
[/csharp]
2. 解决多线程刷新界面控件的问题
[csharp toolbar=”false”]
private void UpdateControls()
{
if (_lblStatus.InvokeRequired)
{
// In the thread, call delegate to flush controls
FlushControls fc = new FlushControls(UpdateControls);
this.Invoke(fc);
}
else
{
_lblStatus.Text = “在这里更新控件内容!”;
_lblStatus.ForeColor = Color.Red;
}
}
// 多线程直接调用UpdateControls()函数即可
[/csharp]
3. Post方式提交URL的方法
[csharp toolbar=”false”]
byte[] buf = null;
if (data != null)
{
ASCIIEncoding encoding = new ASCIIEncoding();
buf = encoding.GetBytes(data);
}
ServicePointManager.Expect100Continue = false;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = _cookie;
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;
request.KeepAlive = false;
if (buf != null)
{
request.ContentLength = buf.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(buf, 0, buf.Length);
reqStream.Close();
}
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream, Encoding.Default);
strResponse = reader.ReadToEnd().Replace(“\n”, “”).Replace(“\r”, “”).Replace(“\t”, “”);
}
[/csharp]
4. Smtp发邮件的方法
[csharp toolbar=”false”]
public static bool SendEmail(string subject, string body)
{
SmtpClient client = new SmtpClient(_config.SmtpServer, _config.SmtpPort);
MailMessage mail = new MailMessage(_config.FromEmail, _config.ToEmail);
bool ret = false;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(_config.Username, _config.Password);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = _config.UseSsl;
mail.IsBodyHtml = true;
mail.Subject = subject;
mail.Body = body;
try
{
client.Send(mail);
ret = true;
}
catch (Exception)
{
}
return ret;
}
[/csharp]
Tags: C#/.NET