Mega Code Archive

 
Categories / Delphi / System
 

Hardlinks and Shortcuts

Title: Hardlinks and Shortcuts Question: How do you create Hardlinks and Shortcuts ? What is the difference between both ? Answer: Shortcuts or *.lnk files are usually found on desktops and are useful to reference something else. But they have a drawback: the target object of a shortcut may change over time. If it is moved, deleted, or simply renamed, the shortcut becomes invalid. Since Windows 2000, Hardlinks are available. Hardlinks are capable of adapting themselves to these changes, due to some form of inner magic of the NFTS file system. If the original target object is moved, deleted or renamed, the hardlink is still valid. Hardlinks look like a true copy of the file, but the necessary disk space is allocated only once. They are useful if you have to copy a large part of a huge number of files without allocation of further disk space. It is easy to create Hardlinks. In the Command Shell ("DOS-Box") you can use the fsutil command : fsutil hardlink create Hardlink_FileName Existing_FileName In a Delphi application, you can call directly the API function CreateHardLink(). The function CreateHardLink can be found in kernel32.dll (for Windows XP or Windows 2000) and is already defined in Windows.pas as part of the Windows API. function CreateHardLink(lpFileName, lpExistingFileName: PChar; lpSecurityAttributes: PSecurityAttributes): BOOL; stdcall; A simple example: if CreateHardLink(PChar('C:\Data\Projects\HardLink\hardlink_1.png'), PChar('C:\Data\Projects\HardLink\1.png'), nil) then ShowMessage('HardLink created'); Creating a shortcut is a bit more complicated and requires in the Age of .NET still ugly COM programming: uses ShlObj, ActiveX, ComObj; procedure CreateShortCut(Filename,Arguments,TargetDir : string); var MyObject : IUnknown; MySLink : IShellLink; MyPFile : IPersistFile; WFileName : WideString; Filepath : string; begin Filepath := ExtractFilePath(Filename); Filename := ExtractFileName(Filename); MyObject := CreateComObject(CLSID_ShellLink); MySLink := MyObject as IShellLink; MyPFile := MyObject as IPersistFile; with MySLink do begin SetArguments(PChar(Arguments)); SetPath(PChar(IncludeTrailingPathDelimiter(Filepath) + Filename)); SetWorkingDirectory(PChar(FilePath)); end; Filename:=ChangeFileExt(Filename,'.lnk'); WFileName := IncludeTrailingPathDelimiter(TargetDir) + Filename; MyPFile.Save(PWChar(WFileName), False); end; Reference: A Programmer's Perspective on NTFS 2000 Part 1: Stream and Hard Link http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/ntfs5.asp