デスクトップ上のショートカットファイルの名前をアプリケーションに変更するユーザーがいます。アプリケーションのアイコンが変更された場合に、ターゲットパスに基づいてショートカットを削除/変更するための最良の方法は何ですか?つまり、ファイル名が変更され続けるため、ファイル名を見つけるのに苦労しています。
3 に答える
FileSystemWatcherクラスを使用する必要があります。
ファイル システムの変更通知をリッスンし、ディレクトリまたはディレクトリ内のファイルが変更されたときにイベントを発生させます。
実際、、、、イベントを利用FileSystemWatcher.Changed
してFileSystemWatcher.Created
、ファイルを制御し続けることができます。FileSystemWatcher.Renamed
FileSystemWatcher.Deleted
MSDN による例を次に示します。
public static void Main()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "mypath";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
ショートカットの名前を変更してもターゲット パスは変更されませんが、C# でショートカットを操作する最善の方法は、IwshRuntimeLibrary
.
ファイルを削除するには、System.IO.File.Deleteメソッドを使用してください
ファイルを変更するには、System.IO.File.AppendTextメソッドを使用できます
以下からのコメントの後に更新します。
ShellClass を使用してショートカットを作成または変更してください。また、Environment.SpecialFolder.DesktopDirectory を使用して、デスクトップから特別なディレクトリを取得する必要があります。
ステップバイステップを示す非常に良い例がここにあります http://www.codeproject.com/Articles/146757/Add-Remove-Startup-Folder-Shortcut-to-Your-App