下麵將完成的展示,使用MAPI介面操作Outlook完成通訊錄更新。 using Microsoft.Office.Interop.Outlook; using Microsoft.VisualBasic; using System; using System.Collections; using ...
下麵將完成的展示,使用MAPI介面操作Outlook完成通訊錄更新。
using Microsoft.Office.Interop.Outlook;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddressBookTool2
{
class Program
{
static void Main(string[] args)
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
bool isAlreadyRunning = false;
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
// 檢查路徑以確保是同一個可執行文件的另一個實例
if (process.MainModule.FileName == current.MainModule.FileName)
{
isAlreadyRunning = true;
break;
}
}
}
if (isAlreadyRunning)
{
}
else
{
while (true)
{
Action();
Thread.Sleep(1000 * 60 * 15);
}
}
}
const string conn = "Server=192.168.100.99;Database=帆軟報表;uid=sa;pwd=dsc";
/// <summary>
/// 動作
/// </summary>
public static void Action()
{
string ipAddress = "192.168.100.99";
Ping ping = new Ping();
PingReply pingReply = ping.Send(ipAddress);
if (pingReply.Status != IPStatus.Success) return;
UpdateClient();
const string sql = "SELECT Guid,應用名稱,版本,備註 FROM 帆軟報表.dbo.版本控制 WHERE 應用名稱 = N'集團通訊錄'";
List<Dictionary<string, object>> list = SelectList(sql, conn);
if (list.Count > 0)
{
string version = list[0]["版本"].ToString();
if (string.IsNullOrEmpty(version)) return;
string path = $"{Environment.CurrentDirectory}\\Version.conf";
if (!File.Exists(path))
{
UpdateAddressBook();
File.WriteAllText(path, version.Trim());
}
else
{
string content = "";
foreach (string item in File.ReadLines(path))
{
content += item;
}
if (content.Trim() != version.Trim())
{
UpdateAddressBook();
File.WriteAllText(path, version.Trim());
}
}
}
}
/// <summary>
/// 更新客戶端
/// </summary>
public static void UpdateClient()
{
string ipAddress = "192.168.100.18";
Ping ping = new Ping();
PingReply pingReply = ping.Send(ipAddress);
if (pingReply.Status != IPStatus.Success) return;
const string sql = "SELECT Guid,應用名稱,版本,備註 FROM 帆軟報表.dbo.版本控制 WHERE 應用名稱 = N'集團通訊錄客戶端'";
List<Dictionary<string, object>> list = SelectList(sql, conn);
if (list.Count > 0)
{
string version = list[0]["版本"].ToString();
string path = $"{Environment.CurrentDirectory}\\ClientVersion.conf";
if (!File.Exists(path))
{
File.WriteAllText(path, version.Trim());
UpdateClientAction();
Environment.Exit(0);
}
else
{
string content = "";
foreach (string item in File.ReadLines(path))
{
content += item;
}
if (content.Trim() != version.Trim())
{
File.WriteAllText(path, version.Trim());
UpdateClientAction();
Environment.Exit(0);
}
}
}
}
/// <summary>
/// 更新客戶端行動
/// </summary>
public static void UpdateClientAction()
{
string batPath = $"{Environment.CurrentDirectory}\\temp.bat";
string cmdText = $"@echo off{Environment.NewLine}timeout /t 3 /nobreak >nul{Environment.NewLine}start {Environment.CurrentDirectory}\\updater.bat \"{Environment.CurrentDirectory}\" \"{Environment.CurrentDirectory}\\AddressBookTool2.exe\"{Environment.NewLine}eixt";
File.WriteAllText(batPath, cmdText, Encoding.UTF8);
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = batPath,
CreateNoWindow = true,
RedirectStandardError = true,
UseShellExecute = false
};
using (Process process = new Process())
{
process.StartInfo = psi;
process.Start();
}
}
/// <summary>
/// 更新通訊錄
/// </summary>
public static void UpdateAddressBook()
{
const string sql = "SELECT 郵箱地址 AS 'emailAddress',姓氏 AS 'firstName',姓名 AS 'lastName', 群組 AS 'group' FROM [帆軟報表].[dbo].[集團郵箱通訊錄] WHERE 郵箱地址 IS NOT NULL AND (姓氏 IS NOT NULL OR 姓名 IS NOT NULL)";
List<Dictionary<string, object>> list = SelectList(sql, conn);
List<Contact> contacts = new List<Contact>();
list.ForEach(it =>
{
string firstName = it["firstName"].ToString()?.Trim();
string lastName = it["lastName"].ToString()?.Trim();
string emailAddress = it["emailAddress"].ToString()?.Trim();
string group = it["group"].ToString()?.Trim();
int index = group.IndexOf(",");
if (index >= 0)
{
string[] groupList = group.Split(',');
groupList.ToList().ForEach(g =>
{
Contact contact = new Contact()
{
FirstName = firstName,
LastName = lastName,
EmailAddress = emailAddress,
Group = g
};
contacts.Add(contact);
});
}
else
{
Contact contact = new Contact()
{
FirstName = firstName,
LastName = lastName,
EmailAddress = emailAddress,
Group = group
};
contacts.Add(contact);
}
});
if (contacts.Count == 0) return;
GeneractionStroe(contacts, false, "通訊錄", true, "湯石集團通訊錄");
GeneractionStroe(contacts, false, "通訊錄", false, "湯石集團通訊錄");
}
public static void GeneractionStroe(List<Contact> contacts, bool order, string fileName, bool CH_zh, string addressBookName)
{
// 繁簡轉換
contacts = ContactsLang(contacts, CH_zh);
// 創建Store,也就是PST檔
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
NameSpace session = outlookApp.GetNamespace("MAPI");
string path = $"{Environment.CurrentDirectory}\\{fileName}.pst";
Store store = GetStore(session, path, 5);
MAPIFolder contactFolder = GetAddressBookFolder(store, addressBookName);
// 移除就的聯繫人
int count = contactFolder.Items.Count;
for (int i = 0; i < count; i++)
{
contactFolder.Items.Remove(1);
}
MAPIFolder deteledItems = store.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems);
count = deteledItems.Items.Count;
for (int i = 0; i < count; i++)
{
deteledItems.Items.Remove(1);
}
// 新增聯繫人
contacts.Distinct(new ContactEqualityComparer()).ToList().ForEach(contact =>
{
if (!string.IsNullOrEmpty(contact.FirstName) && !string.IsNullOrEmpty(contact.LastName))
{
ContactItem newContact = contactFolder.Items.Add(OlItemType.olContactItem);
OrderContactItem(contact.FirstName, contact.LastName, order, newContact);
newContact.Email1Address = contact.EmailAddress;
newContact.Save();
System.Runtime.InteropServices.Marshal.ReleaseComObject(newContact);
newContact = null;
}
});
// 新增群組
contacts.GroupBy(it => it.Group).Select(it => new
ContactGroup()
{
Group = it.Key,
Contacts = it.ToList()
}).ToList().ForEach(it =>
{
if (!string.IsNullOrEmpty(it.Group))
{
DistListItem dist = contactFolder.Items.Add(OlItemType.olDistributionListItem);
it.Contacts.ForEach(contact =>
{
Recipient recipient = outlookApp.Session.CreateRecipient(contact.FirstName + contact.LastName + "(" + contact.EmailAddress + ")");
if (recipient.Resolve())
{
dist.AddMember(recipient);
}
});
dist.DLName = it.Group;
dist.Save();
// 確保所有項已從新創建的PST中釋放
System.Runtime.InteropServices.Marshal.ReleaseComObject(dist);
dist = null;
}
});
// 清理Outlook對象,避免記憶體泄漏
System.Runtime.InteropServices.Marshal.ReleaseComObject(session);
System.Runtime.InteropServices.Marshal.ReleaseComObject(outlookApp);
outlookApp = null;
session = null;
}
/// <summary>
/// 獲取Store
/// </summary>
/// <param name="session">命名控制項</param>
/// <param name="target">目標pst檔</param>
/// <param name="count">最大遞歸次數</param>
/// <returns></returns>
public static Store GetStore(NameSpace session, string target, int count)
{
Store store = null;
foreach (Store it in session.Stores)
{
if (it.FilePath == target)
{
store = it;
break;
}
}
if (store == null && count > 0)
{
session.AddStore(target);
return GetStore(session, target, count--);
}
return store;
}
/// <summary>
/// 獲取聯繫人文件夾
/// </summary>
/// <param name="store">Store實例</param>
/// <param name="name">文件夾名稱</param>
/// <returns></returns>
public static MAPIFolder GetAddressBookFolder(Store store, string name)
{
MAPIFolder folder = null;
Folders folders = store.GetDefaultFolder(OlDefaultFolders.olFolderContacts).Folders;
foreach (MAPIFolder item in folders)
{
if (item.Name == name)
{
folder = item;
break;
}
}
if (folder == null)
{
folder = store.GetDefaultFolder(OlDefaultFolders.olFolderContacts).Folders.Add(name);
folder.ShowAsOutlookAB = true;// 設置成聯繫人
}
return folder;
}
/// <summary>
/// 轉換語言,簡體轉繁體
/// </summary>
/// <param name="contacts">聯繫人信息集合</param>
/// <param name="lang">是否轉繁體</param>
/// <returns></returns>
public static List<Contact> ContactsLang(List<Contact> contacts, bool lang)
{
List<Contact> result = new List<Contact>();
if (lang)
{
return contacts;
}
else
{
contacts.ForEach(it =>
{
it.FirstName = Strings.StrConv(it.FirstName, VbStrConv.TraditionalChinese);
it.LastName = Strings.StrConv(it.LastName, VbStrConv.TraditionalChinese);
it.Group = Strings.StrConv(it.Group, VbStrConv.TraditionalChinese);
result.Add(it);
});
}
return result;
}
/// <summary>
/// 轉換聯繫人的姓與名位置
/// </summary>
/// <param name="firstName">姓氏</param>
/// <param name="lastName">名字</param>
/// <param name="order">順序</param>
/// <param name="contact">聯繫人實例</param>
public static void OrderContactItem(string firstName, string lastName, bool order, ContactItem contact)
{
if (order)
{
contact.FirstName = firstName;
contact.LastName = lastName;
}
else
{
contact.LastName = firstName;
contact.FirstName = lastName;
}
}
public struct Contact
{
public string FirstName;
public string LastName;
public string EmailAddress;
public string Group;
}
public struct ContactGroup
{
public string Group;
public List<Contact> Contacts;
}
public class ContactEqualityComparer : IEqualityComparer<Contact>
{
public bool Equals(Contact x, Contact y)
{
return x.FirstName == y.FirstName && x.LastName == y.LastName && x.EmailAddress == y.EmailAddress;
}
public int GetHashCode(Contact obj)
{
return obj.FirstName.GetHashCode() ^ obj.LastName.GetHashCode() ^ obj.EmailAddress.GetHashCode();
}
}
/// <summary>
/// 執行select語句
/// </summary>
/// <param name="sql">select語句</param>
/// <param name="connection">資料庫鏈接語句</param>
/// <returns>List的結果</returns>
/// <exception cref="System.Exception"></exception>
public static List<Dictionary<string, object>> SelectList(string sql, string connection)
{
if (sql == null || connection == null || sql == "" || connection == "")
throw new System.Exception("未傳入SQL語句或者Connection鏈接語句");
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
SqlConnection conn = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader sqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sqlDataReader.Read())
{
int count = sqlDataReader.FieldCount;
if (count <= 0) continue;
Dictionary<string, object> map = new Dictionary<string, object>();
for (int i = 0; i < count; i++)
{
string name = sqlDataReader.GetName(i);
object value = sqlDataReader.GetValue(i);
map.Add(name, value);
}
list.Add(map);
}
conn.Close();
return list;
}
catch (System.Exception)
{
conn.Close();
return null;
}
}
}
}
updater.bat 更新用的
@echo off
set "source=\\192.168.100.18\mis\21.email-plugin\AddressBookTool"
:: 使用Robocopy複製除了version.conf之外的所有文件和目錄
robocopy "%source%" "%1%" /E /XD Version.conf ClientVersion.conf
:: 檢查並有條件地複製version.conf
if not exist "%1%\Version.conf" (
copy /Y "%source%\Version.conf" "%1%"
)
:: 啟動程式
cd /d "%1%"
start "" "%2%"
exit
setup.bat 安裝用
@echo off
set "REG_PATH=HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\AddressBookTool"
set "client_bat=C:\TONS\AddressBookTool\start.bat"
set "folder=C:\TONS\AddressBookTool"
set "source=\\192.168.100.18\mis\21.email-plugin\AddressBookTool"
:: 使用Robocopy複製除了version.conf之外的所有文件和目錄
robocopy "%source%" "%folder%" /E /XD version.conf
:: 檢查並有條件地複製version.conf
if not exist "%folder%\version.conf" (
copy /Y "%source%\version.conf" "%folder%"
)
:: 配置環境變數
reg query %REG_PATH% >nul 2>nul&&goto A||goto B
:B
reg add "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v AddressBookTool /t REG_SZ /d %client_bat% /f
:A
start %client_bat%
exit
start.bat 啟動用
@echo off
set "environment=C:\TONS\AddressBookTool"
set "client=C:\TONS\AddressBookTool\AddressBookTool2.exe"
:: 啟動程式
cd /d "%environment%"
start "" "%client%"
exit