甲方爸爸要求把引用的資料(大部分是檔案)放到一個檔案夾下,把檔案夾路徑傳回;考慮到伺服器空間問題,選擇把資源檔案的快捷方式放到檔案夾裡。
但資源檔案是中文名,在使用 IWshShortcut 的時候總是出錯,耗時快兩個點才定位出來居然是中文的問題//還以為2018了大部分庫也應該能支援中文了然而圖拿衣服啊
最終解決方案
添加引用->COM->Microsoft Shell Controls And Automation
/// <summary>
/// 為檔案建立快捷方式
/// </summary>
/// <param name="fileName">源檔案路徑</param>
/// <param name="Folder">目标檔案夾</param>
public static void CreateShortcut(string fileName, string Folder)
{
try
{
object[] para = new object[] { fileName, Folder };
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
createShortcutWithShell(para);
}
else {
Thread staThream = new Thread(new ParameterizedThreadStart(createShortcutWithShell));
staThream.SetApartmentState(ApartmentState.STA);
staThream.Start(para);
staThream.Join();
}
}
catch (Exception e)
{
throw;
}
}
static void createShortcutWithShell(object param) {
object[] args = (object[])param;
string fileName = (string)args[0];
string Folder = (string)args[1];
if (!File.Exists(fileName)) { throw new Exception("資源檔案<" + GetFileShortName(fileName) + ">不存在!"); }
InitLocalPath(Folder);
var lnkPath = Path.Combine(Folder, GetFileShortName(fileName) + ".lnk");
// Create empty .lnk file
System.IO.File.WriteAllBytes(lnkPath, new byte[0]);
// Create a ShellLinkObject that references the .lnk file
Shell32.Shell shl = new Shell32.Shell();
Shell32.Folder dir = shl.NameSpace(Folder);
Shell32.FolderItem itm = dir.Items().Item(GetFileShortName(fileName) + ".lnk");
Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;
// Set the .lnk file properties
lnk.Path = fileName;
lnk.Save(lnkPath);
}
參考資料:
https://stackoverflow.com/questions/31403956/exception-when-using-shell32-to-get-file-extended-properties
https://stackoverflow.com/questions/13542005/create-shortcut-with-unicode-character?lq=1
下面簡單說明一下:
1. IWshShortcut 對Unicode character并不支援,展現在源檔案不能帶有中文,且建立的.lnk檔案也不能帶有中文。
說到這也不知道為啥國内的資料都是用的這個庫來建立快捷方式。。。
2. Shell21.Shell new的時候也會報“Unable to cast COM object of type 'Shell32.ShellClass' to interface type 'Shell32.IShellDispatch6'. ”的錯,必須用STA來跑shell。
3. 當然,至此,建立中文lnk檔案的問題是解決了。。。但通過中文lnk檔案擷取目标檔案也不能用 IWshShortcut ……可以說非常麻煩了。。。。
于是最終我們不用這種方式引用資料了。。幾個小時白幹。。感到了開心
