Wpf file browser dialog select shortcut file - c#

I am using on WPF Win32 file browser dialog to select a file in the filesystem. Now my problem is, when I select an shortcut file ending with .ink, it shows the application path not the shortcut(.ink) path.
For example I want to select snoop shortcut
as filepath, I've got.
How can I get the path from shortcut not from application?
Update
I am trying restrict with
Win32.OpenFileDialog ofd = new Win32.OpenFileDialog();
ofd.Filter = "Link (*.lnk)|*.lnk";
but only .lnk it is possible to select. It should be possible to select other files too, not only .lnk file.

You must use OpenFileDialog.DereferenceLinks property.
Gets or sets a value indicating whether a file dialog returns either the location of the file referenced by a shortcut or the location of the shortcut file (.lnk).
odf.DereferenceLinks = false;
For the update question, just add All Files|*.*| :
ofd.Filter = "All Files|*.*|Link (*.lnk)|*.lnk";

Related

C#: opening a text file stored within the same project as the app

I managed to open a text file using an absolute path (in Visual Studio 2017) although if I change the location of my Solution folder the whole code would not work anymore as the actual physical path has changed and the code can not reference an existing location anymore.
I tried to create a text file within the same project and I would now like to open this file in my code, so if the location of the whole Solution changes the program can still work, would anyone be so kind to help me fix this issue?
I have also looked online for some different solution using code that references the current directory but I can't get my head around it as the current directory seems to be bin/debug and if I try to insert the file there the code doesn't recognize the location (also it doesn't look like a clean solution to me).
This is the code I am using so far in a WPF app, the whole purpose is to open the content of the text file containing countries listed line by line and to add them to a list box which will be displayed when a checkbox will be ticked.
private void listCountry_Initialized(object sender, EventArgs e)
{
listCountry.Visibility = Visibility.Hidden;
string path = "C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\StudentRecord\\country.txt";
if (File.Exists(path))
{
string[] myCountryFile = File.ReadAllLines(path);
foreach (var v in myCountryFile)
{
listCountry.Items.Add(v);
}
}
}
This is a great use case for OpenFileDialog Class.
Represents a common dialog box that allows a user to specify a filename for one or more files to open.
Here is the example of use, from the documentation.
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
Assuming C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\ is your project, and StudentRecord\\country.txt is a project folder and file in your project - you need change "Copy to Output Directory" to be "Always Copy" or "Copy If Newer" and "Build Action" to "Content" for the file in your project.
As you can see from the screenshot above, the folder structure for this content is created as well.
Then change your path assignment to be something like the following:
string path = string.Join(#"\", Application.ExecutablePath, #"StudentRecord\country.txt");
Clean and simple, place the file you want to open next to where the executable is generated, remember the executable path changes depending to if your project is in Debug or Release build mode. Now set:
string path = "country.txt";
By only providing a filename, the file is looked for in the same folder as the executable. Just remember that when you move the executable you must also move the file to the same place, but if you move the entire project folder then you're already set.
However, if you want to keep your file in a fixed location regardless of where you have your executable and/or VS project files, then the simplest path for it is:
string path = "C:\\country.txt";
This is an absolute path, but it's quite simple and very robust to changes, you would have to change the drive letter to break it and if C: is where your operating system files are then you probably won't do that.
If you don't like to have your files around in your root, you can always have a path like this:
string path = "C:\\ProjectNameFiles\\country.txt";
Or if you prefer to maintain a hierarchy of projects then you can use:
string path = "C:\\MyProjectsFiles\\ProjectName\\country.txt";
With this, every project can have a directory for the files it needs to open. These are all absolute paths, but are notably simpler than the one you posted, and they have a more fixed and organized structure.

how to Save File using C# Windows Application

I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));

How to automatically select an already existing file in a directory

I am trying to replicate the standard save file process where, if there already exists a file with the necessary file extension, it is pre-selected in the SaveFileDialog. In my program I am using SaveFileDialog to allow the user to select the path for the file on the system. Upon save, it will automatically open to the path that the last saved file was, but the user has to re-select it.
Here is where I think something like this would come into play in my code:
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = ".cct"; //The file extension
Nullable<bool> result = dlg.ShowDialog(); //Lets user select path
//**I'm guessing that the "pre-select" operation I am talking about
//would go here
directory = Path.GetDirectoryName(dlg.FileName); //Directory = File path on system
I have looked at the CheckFileExists property and it says that it "Gets or sets a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist." So it looks like it's more focused around checking whether or not the user enters a new file name.
How do I make it so that the previously saved file with the same extension is highlighted or selected in the SaveFileDialog if one is found upon save?
You can do a couple of things.
You could restore the path the user last saved with by setting dlg.RestoreDirectory = true.
Set the FileName before you show the dialog and it will automatically show that folder and insert the file name using dlg.FileName
http://msdn.microsoft.com/en-us/library/microsoft.win32.savefiledialog(v=vs.110).aspx

Save a file in folder opened by dialog box

My program has a treeview which lists files from a remote computer. What I need to do is to copy these files from remote into one of my local folders. I wish that when I right click the file in treeview, a dialog box shows up for me to choose a folder, and then I click "OK" in the dialog box, my clicked file could be saved inside that folder.
Since the path of the files in remote is unc path, I'm using
File.Copy(string remote_address, string local_address)
to copy the files. As i said before I need a dialog window to choose folders. So I've tried using a FolderBowserDialog, however its SelectedPath property returns me only the path to the folder not including the folder's name! And I haven't found any property to return me the folder's name.
So my questions are:
If there's a way allowing me to use FolderBowserDialog, that I could get the full path of the location where I save my file?
If there's another method allowing me to copy or download the files from remote, like using SaveFileDialog. The problem is I don't know how to us it to do this.
The following should work:
var fbd = new FolderBrowserDialog();
if(fbd.ShowDialog() == DialogResult.OK)
{
var localPath= Path.Combine(fbd.SelectedPath, Path.GetFilename(remote_address));
File.Copy(remote_address, localPath);
}
I'm not sure which "SavePath" property you are referring to, as FolderBrowserDialog has no such property. The property you are looking for is called SelectedPath.
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.ShowDialog();
string local_address = dlg.SelectedPath;
After you call the FolderBrowserDialog's ShowDialog() method it will return a variable indicating what button the user pressed (ie, Ok or Cancel)
after you make sure the user had used "Ok" to indicate they want to proceed with the operation, you can access the "SelectedPath" field which will give you the full local path they selected.
You can then get the final path by calling
System.IO.Path.Combine(fbd.SelectedPath,remoteFileName);
I'm assuming that fbd is your FolderBrowserDialog instance and remoteFileName should contain just the filename part of the remote file (eg. "MyFile.txt");
If you want to separate the filename from the full remote path, use
var remoteFileName = System.IO.Path.GetFileName(remotePath);
That being said, what a user would typically expect is not a folder browser dialog, but the save file dialog.
you can initialize the save file dialog with a filename, leaving the user to select a folder and possibly change the intended file name as well if they wish.
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = remoteFileName;
sfd.ShowDialog();
sfd.FileName // now contains the full path to the file that the user has selected
don't forget to take the result from the ShowDialog() call to make sure the user didn't cancel out of the save dailog!

How to create a folder and ask the user where to save it to in C#?

I think that all i need is in the question. I placed my method in my Form.Load I can either create a folder or open a SaveFileDialog but not both at once.
If someone could help me please.
Thanks.
SaveFileDialog lets the user choose a file location that already exists. If not, they can create a folder within the dialog as #Bali suggested.
If you want the user to be able to create a new folder without using the dialog then you'll need to let the user type the path (e.g. in a textbox). Then you can check to see if the directory exist using Directory.Exist, and if not, create it using Directory.Create.
void CheckPath(string path)
{
var dir = Path.GetDirectoryName(path);
if( !String.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.Create(dir);
}
Open a FolderBrowserDialog for the user with the title (Description property) set to something like "Choose an existing folder or create a new one". Do not forget to set its ShowNewFolderButton property to true.
You can also use the FolderBrowserDialog to ask the user only to select the containing ("parent") folder, and create the new folder yourself by calling Directory.CreateDirectory. In this case, ShowNewFolderButton should be false.
This would be to create a new directory
Directory.CreateDirectory(#"C:\Your File Path Here");
This would be to open a file. You can select where it opens the initial directory of the file by changing the path.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = (#"C:\Your starting File Path");
openFileDialog1.Filter = "All Files (*.*)|*.*";
openFileDialog1.Title = "Select a File";

Categories

Resources