How to read all data shortcut using OpenFileDialog? - c#

I'm making a launcher to open all applications on my computer. But I do not know how to read the parameters of the opened file is a shortcut. I have tried using:
openFileDialog.DereferenceLinks = false; //and true
Can anyone help me? My code is here:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog od = new OpenFileDialog();
od.DereferenceLinks = false;
od.Multiselect = false;
od.SupportMultiDottedExtensions = true;
if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (System.IO.Path.GetExtension(od.FileName).ToLower().Equals(".lnk"))
{
MessageBox.Show(//xxxxxxx how to sho the parameter?); for example output c:\\.....\hl.exe -a -b -c -d -e 29332
}
}
}

I can't understand what the problem is here. You said you've already discovered the FileDialog.DereferenceLinks property, which does exactly what you want.
When it is set to true, the dialog box dereferences all shortcuts, returning the path of the item that they point to, rather than the path of the shortcut file itself. Only when it is set to false will you get files with a .lnk extension returned from the dialog.
So the code that you have just added to the question is wrong (or at least, makes things much more difficult for you than they need to be). It should look more like this:
OpenFileDialog od = new OpenFileDialog();
od.DereferenceLinks = true; // set this to true if you want the actual file
od.Multiselect = false;
od.SupportMultiDottedExtensions = true;
if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// You will never get a path to a shortcut file (*.lnk) here.
Debug.Assert(!String.Equals(System.IO.Path.GetExtension(od.FileName),
".lnk",
StringComparison.OrdinalIgnoreCase));
// ... do something with the file
}
Otherwise, dereferencing shortcut files takes a fair bit of effort. You do so using the IShellLink COM interface, which I don't believe is wrapped explicitly by any part of the .NET BCL. You'll need to write the code to use it yourself. I can't imagine why you'd need to in this case.
That is what you'll have to do if you need to read the arguments from a shortcut file.
Set the OpenFileDialog.DereferenceLinks property to false so that you get shortcut files returned.
You probably also want to set the OpenFileDialog.Filter property to Shortcut files (*.lnk)|*.lnk in order to ensure that the user can only select shortcut files in the dialog.
Once the user has selected a shortcut file, create an IShellLink object for that file.
If that succeeds, use the GetPath method to obtain a string containing the path and file name of the shortcut file, and GetArguments method to obtain a string containing the command-line arguments associated with that shortcut file.
Finally, append the arguments string to the end of the path string.
You can either write the wrapper code to use the IShellLink COM interface from .NET yourself, search online to find one that's already been written (no guarantees about its quality, though), or add a reference to the ShellLinkObject class which is designed for scripting but still usable from .NET.

Related

OpenFileDialog - How to prevent the default directory from being overwritten?

I'm trying to find a way to reset the initial/default directory after closing an OpenFileDialog. Consider the following example:
using (OpenFileDialog openFile = new OpenFileDialog())
{
// Example: This opens in the 'Desktop' directory
// User navigates to 'Documents' directory in the Form before selecting a file
DialogResult result = openFile.ShowDialog();
if (result == DialogResult.OK) MessageBox.Show(openFile.FileName);
}
// Somewhere else, this code then runs
using (OpenFileDialog openFile = new OpenFileDialog())
{
// Problem: This now opens in 'Documents' directory. Not good!
// How to open using the same default directory (ie: Desktop)?
DialogResult result = openFile.ShowDialog();
if (result == DialogResult.OK) MessageBox.Show(openFile.FileName);
}
Just to be clear, 'Desktop' is just an example, I won't actually know the initial directory as it's stored in the registry (if I understand correctly).
I tried using the RestoreDirectory option. This did not seem to have any effect. From what I've read elsewhere it's supposed to reset the Environment.CurrentDirectory back to its original value, which sounds reasonable. However, I don't think OpenFileDialog even uses Environment.CurrentDirectory since the value is never changed, and never matches what OpenFileDialog opens with (unless I manually browse to it).
Is there anything I might be missing here? Does anyone know how to stop overwriting whichever directory variable OpenFileDialog uses as its default?
The default directory is stored in the following registry key on Windows 7.
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32
IIRC, this could be different on other OS's, so you might want to find out the exact directory depending on your OS version.
So what you could do is to grab that value when your application launches, and save it in the memory, and set that to OpenFileDialog.InitialDirectory every time before you open the dialog.

How do I Use OpenFileDialog to select files or paths

I am writing a WPF / C# application, and would like to enable a user to select one (or multiple) files, or one (or multiple) folders, without having to select which option they use initially, but intentionally. In my opinion, the best way to acchieve this goal would be to have a standard FolderBrowserDialog, and as long as the user does not seelct a file, but browses to a path, clicking the open button should select that path.
Practically, this solution does not work, because OpenFileDialog does not allow empty selections, you can hit "open", but nothing will happen. There is one workaround descriped here which allows to enter a fake name like "Selected Folder." as filename. which can afterwards be filtered out, which is a workaround, but not a nice one:
http://www.codeproject.com/Articles/44914/Select-file-or-folder-from-the-same-dialog
This solution has two important weaknesses:
1.) you will have to filter for the fake name
2.) if you paste a filename manually, or select a file first, and then switch the selection to a folder instead, the fake name is not inserted automatically.
of course I am aware there is something like FolderBrowserDialog, which I omit using even if I only wanted to select folders and not files. The reason: this dialog has no possibility to paste paths from clipboard, and I find it annoying to navigate all the way, I rather copy paths from somewhere and paste them, which works perfectly fine in OpenFileDialog, but not in FolderBrowserDialog. Besides, FolderBrowserDialog does not allow to select files and folders.
I have googled a lot, but do not find satisfying solutions, although I am sure many people must obviously face this problem.
As mentioned, the most elegant way for me would be to make the OpenFileDialog simply allow empty Filename boxes when clicking Open - any way to acchieve this?
Thanks alot.
Letting a user select a directory OR a file using the same dialog is not practical nor intuitively possible.
However, if you want a solution for selecting a Folder, here it is :
If you don't want to create a custom dialog but still prefer a 100% WPF way and don't want to use separate DDLs, additional dependencies or outdated APIs, I came up with a very simple hack using WPF's Save As dialog for actually selecting a directory.
No using directive needed, you may simply copy-paste the code below !
It should still be very user-friendly and most people will never notice.
The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.
It is a big hack for sure, but maybe it will do the job just fine for your usage...
In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...
// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
string path = dialog.FileName;
// Remove fake filename from resulting path
path = path.Replace("\\select.this.directory", "");
path = path.Replace(".this.directory", "");
// If user has changed the filename, create the new directory
if (!System.IO.Directory.Exists(path)) {
System.IO.Directory.CreateDirectory(path);
}
// Our final value is in path
textbox.Text = path;
}
The only issues with this hack are :
Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...
Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

How can I code defensively against potential unorthodox hard drive letters?

I can set a SaveFileDialog's InitialDirectory property to where my app will usually be installed like so:
saveFileDialog1.InitialDirectory = #"C:\Program Files\Waltons\Mountains";
...but as "there is one in every crowd," some may use a drive letter other than C for their hard drive? How can I set the InitialDirectory to whichever drive letter the user has specified?
UPDATE
I tried Alexei's code (had to change "Concat" to "Combine" and remove a superfluous ")":
saveFileDialog1.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), #"Waltons\Mountains");
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
// TODO: Finish
}
...but it does not open C:\Program Files\Waltons\Mountains
UPDATE 2
Saeb's suggestion seems to work, as the save file dialog opens in C:\Waltons\Mountains\bin\Debug
...which I hope/reckon would correspond to C:\Waltons on the user's machine (or D:\Waltons or Z:\Waltons or whatever).
I would have to append the "\Maps" I guess for the user - check that it's not running in Visual Studio or something and append that in that event.
Location that is writable by normal user would be better default location for save dialog. I.e. "my documents" via Environment.GetFolderPath passing one of Environment.SpecialFolder values:
var pathToMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.Personal));
If you need location where your program installed by default like program files
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "MyFolder");
or if you need path relative to program check How can I get the application's path in a .NET console application?.
Note that locations above are not writable by normal users and even admin unless you turn off UAC or explicitly "run as administrator" or change default permissions on these folders (either of approaches to bypass default permission have its drawbacks and one should perform serious security review if allowing regular users to write in programs/system folders).
Don't use hardcoded driver letters. Find the path in runtime. e.g.:
saveFileDialog1.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
You can use the environment variable systemroot to get the drive. Try opening a cmd prompt and entering set to see a list of all the environment variables avaliable and then use System.Envrionment.GetEnvironmentVariable ("systemdrive") and combine that with the rest of your path.

Passing a C# string to VBscript

I am using a windows form and am trying to pass a string to a vbscript. The program is asking the user to select a folder, I am trying to take the folder selection and pass it through to the vbscript.
C# Code:
String SelectedFolder = #"C:\Users";
folderBrowserDialog1.SelectedPath = SelectedFolder;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
//Set selectedFolder equal to the folder that was choosen
SelectedFolder = folderBrowserDialog1.SelectedPath;
//Call VBScript
System.Diagnostics.Process.Start(".vbsPath");
VBScript:
TargetFolder = Request.QueryString("SelectedFolder")
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(TargetFolder)
Set colItems = objFolder.Items
For Each objItem in colItems
objItem.InvokeVerbEx("Print")
Next
Any help would be greatly appreciated. Thank you
C# side
Use the Process.Start overload that accepts command-line parameters:
System.Diagnostics.Process.Start("C:\path\to\my.vbs", selectedFolder);
If the selectedFolder can contain spaces (which is likely to happen), you should enclose the argument in quotes.
System.Diagnostics.Process.Start("C:\path\to\my.vbs",
"\"" + selectedFolder + "\"");
In fact, if the path can contain quotes and/or trailing backslashes, escaping gets a lot more complicated, see these questions (and others) for details: Escape command line arguments in c#, Passing command-line arguments in C#.
VBScript side
In your VBScript, read the first command line parameter:
targetFolder = WScript.Arguments.Item(0)
You could write the string to a file which both sets of code can access, or a database. That way it won't matter which programming language you are using at all e.g. could be C# to PHP.
Write file:
string content = "folder=" + folder;
System.IO.StreamWriter file = new System.IO.StreamWriter(#"c:\config.txt");
file.WriteLine(content);
file.Close();
Read file:
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\config.txt");
string content = file.ReadToEnd();
// extract value of folder setting here
file.Close();
(Of course the reading would need to be in VB, but would be very similar. Note: code based on: MSDN Example)
Going back and forth from VBScript to C# is adding a lot of complexity. If possible, it would really be easier to choose one or the other.
You can do anything in C# that you can in VBScript. (How you do it is probably different, but you can do all the same tasks - file access, database access, etc.) If it's feasible, you may be better off just working in C#.
I'm doing a bit of a guess based on the context of the question here, but I'm trying to answer in my own head why you'd want to do this, and the only thing I can think of is that you don't know how to display a folder dialog box in VBScript, so you're resorting to trying to do it in C#. Is that correct?
If so, you can show a folder dialog in VBScript as shown here: http://www.robvanderwoude.com/vbstech_ui_browsefolder.php

Getting the last opened file in fileopen dialog box

In FileOpen or FileSave dialogbox when I call them, they automatically go to the last opened path. This happens even if I close my application and open it. But how to get that path/file name to a textbox or variable?
it seems a bit weired but under Windows 7 it works with the folling:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
Try it and tell me if you need further help.
Presumably the information is stored somewhere in the depths of the registry (it's done by the unmanaged control to which OpenFileDialog is only a wrapper). The easiest would probably be to persist the path the last time the dialog was closed in your application somewhere where you can access it.
As mentioned here: What does the FileDialog.RestoreDirectory Property actually do?
They use the path from Environment.CurrentDirectory.
I am having a similar problem to Vicky, which goes as follows. I am developing in Visual Basic 2008 Express Edition under Vista Business SP2.
I have an application with an OpenFileDialog and a SaveFileDialog. When I call the OpenFileDialog on first running the application, it defaults to the directory from which the Application last opened/saved a file. However, this directory IS NOT "Environment.CurrentDirectory" which is set to "C:\Users\Brian\Documents\Visual Studio 2008\Projects\IFPM Analysis\IFPM Analysis\bin\Debug" and is not changed by either the OpenFileDialog or SaveFileDialog.
Later on in the Application, I call the SaveFileDialog, with the initial directory property (.InitialDirectory) set in the code to a default directory. When I subsequently call the OpenFileDialog, it defaults to the directory used by the SaveFileDialog. All the time, the value of "Environment.CurrentDirectory" is unchanged.
So, my question is, where is the directory that is being used by the OpenFileDialog and SaveFileDialog being stored? I assume it is something to do with the underlying FileDialog class, and I know persists even after the Application has been closed and restarted.
Ideally I want to be able to store the directory selected by the user from the OpenFileDialog and reset it after I have used the SaveFileDialog. While I can use the InitialDirectory property of the OpenFileDialog within the Application, this doesn't help me when I close the Application and restart it. Sadly, the typical user actions are:
start Application
open file with OpenFileDialog
save file with SaveFileDialog
leave Application
This means that when the user comes back to the Application, the default directory is the "wrong" one. I know that I can save the last used directory from the OpenFileDialog in my own configuration file so that it will persist outside of the Application, but that seems a little silly when Windows provides me with the same functionality, if only I knew where to look!
Any help gratefully received!
Thanks,
Brian.
The recent opened files list is stored in 2 places:
Recent Folder: The recent folder is usually located under C:\Documents and Settings[Your Profile]\Recent (The path is different under Windows Vista), and it contains shortcuts to the recently opened files.
Registry: Each time that a file is selected in save/open dialog-box, the filename is added to the files list under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSaveMRU
This method can help you to get the list:
public static string GetLastOpenSaveFile(string extention)
{
RegistryKey regKey = Registry.CurrentUser;
string lastUsedFolder = string.Empty;
regKey = regKey.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU");
if (string.IsNullOrEmpty(extention))
extention = "html";
RegistryKey myKey = regKey.OpenSubKey(extention);
if (myKey == null && regKey.GetSubKeyNames().Length > 0)
myKey = regKey.OpenSubKey(regKey.GetSubKeyNames()[regKey.GetSubKeyNames().Length - 2]);
if (myKey != null)
{
string[] names = myKey.GetValueNames();
if (names != null && names.Length > 0)
{
lastUsedFolder = (string)myKey.GetValue(names[names.Length - 2]);
}
}
return lastUsedFolder;
}
Success!
Iordan

Categories

Resources