Reputation: 21
There are Internet Shortcuts, that you can download and when you click on them, your browser opens the link, is there any way to read the Url from the file, using c#?
C# just says the file doesn't exist, for example when I do File.Exists() and in brackets the correct directory, the outcome is always false.
Upvotes: 1
Views: 576
Reputation: 16564
C# just says the file doesn't exist, for example when I do File.Exists() and in brackets the correct directory, the outcome is always false.
If you can see the shortcut in Windows File Explorer but you're getting false from File.Exists()
then you're almost certainly using the wrong filename.
In File Explorer the file extension for Internet Shortcuts (*.url
) and Shortcuts (*.lnk
) are explicitly hidden, regardless of your settings. To get the full path of the file you can select it in File Explorer and then use the Copy Path
option in the Home
ribbon. This will give you the full path and filename of the file regardless of settings or other things that manipulate the name.
As for extracting the URL from an Internet Shortcut (*.url
) file... they're simple INI files. You can read the contents of the file as a simple text file and look for the line starting URL=
. Trim the start of the line and you have your URL.
For example, here's the content of an Internet Shortcut file for Stack Overflow I just created on my desktop:
[InternetShortcut]
URL=http://stackoverflow.com
Extracting the URL from that is fairly simple:
static string? GetURLFromShortcut(string shortcutFilePath)
{
// Confirm that the file exists.
if (!File.Exists(shortcutFilePath))
return null;
// Check the extension is what we expect.
if (string.Compare(Path.GetExtension(shortcutFilePath), ".url", true) != 0)
return null;
// Read lines until we find the "URL=" line.
using var reader = File.OpenText(shortcutFilePath);
while (reader.ReadLine() is string line)
{
if (line.StartsWith("URL=", StringComparison.OrdinalIgnoreCase))
return line[4..];
}
// Hit end of file, just return null.
return null;
}
Upvotes: 2