OpenFileDialog box with multiselect, .filenames receiving same name multiple times - c#

I have a multi-select OpenFileDialog box (named GetFiles) that loops through all the selected files and displays their path in a listbox. Problem is, when all the files are selected and added, it displays the same filename. Here is all the code:
if (GetFile.ShowDialog() == DialogResult.OK)
foreach (string filename in GetFile.FileNames)
{
FileNameList.Items.Add(GetFile.FileName);
}
I feel like there is something really simple that I'm missing....any help will be greatly appreciated

Yes, you are adding the same filename each time using GetFile.FileName. You need to use your variable filename:
if (GetFile.ShowDialog() == DialogResult.OK)
foreach (string filename in GetFile.FileNames)
{
FileNameList.Items.Add(filename);
}

Yes, you're using GetFile.FileName when adding to the list rather than the enumerated value filename.
Try this instead:
if (GetFile.ShowDialog() == DialogResult.OK) {
foreach (string filename in GetFile.FileNames) {
FileNameList.Items.Add(filename);
}
}

Related

how to go next line in ListBox?

hey guys i wanna to load a File path in my listBox.
everything is ok
i just have a problem that is when i Close the app and then open it again
loaded files are in the one lane and it recognize them as one item in listBox
i tried to use "\n" , "\r" none of these works...
so what u guys suggest?
(i save user changes in App Setting to read them later)
private void Form1_Load(object sender, EventArgs e)
{
if (Properties.Settings.Default.FileList != string.Empty)
{
fileListBox.Items.Add(Properties.Settings.Default.FileList);
}
UnlockForm f2 = new UnlockForm();
if (Properties.Settings.Default.PasswordCheck == true)
f2.ShowDialog();
else
return;
}
private void button1_Click_1(object sender, EventArgs e)
{
op = new OpenFileDialog();
op.Title = "Select your stuff";
op.Filter = "All files (*.*)|*.*";
if (op.ShowDialog() == DialogResult.OK)
{
fileName = op.FileName;
fileListBox.Items.Add(fileName);
}
Properties.Settings.Default.FileList += fileName+"\n";
Properties.Settings.Default.Save();
}
When creating the property in settings designer:
Set the name to whatever you want, for example Files
Set the type as System.Collections.Specialized.StringCollection
Set the scope as User
If you want to have some default values, use ... in Value cell to edit default value.
Then you can easily set it as DataSource of the ListBox.
listBox1.DataSource = Properties.Settings.Default.Files;
Also to add some values:
Properties.Settings.Default.Files.Add("something");
Properties.Settings.Default.Save();
If you added something to the Files, if you want the ListBox shows the changes, set DataSource to null and then to Files again.
It looks like you have defined your FileList as String in our App Settings. There are two ways you can approach this.
a) Using FileList as Collection.
You can change the Type of FileList to StringCollection in your App Settings. Then, you can add items to your list as follows
fileListBox.Items.AddRange(Properties.Settings.Default.FileList.Cast<string>().ToArray());
b) Using FileList as String.
If you really want to retain Properties.Settings.Default.FileList as string, you would need to split it on the run using your delimiter character (let's say ';')
fileListBox.Items.AddRange(Properties.Settings.Default.FileList.Split(new[] { ';' },StringSplitOptions.RemoveEmptyEntries));
In your case, a collection might be a better approach unless you have specific reasons outside the scope of OP to use string.

Force File Browser to Sort files by Name

I have a button that opens a file browser and select multiple files, then adds them to a ListView.
How can I force the Browser Dialog Box to always sort the files by name before being added to the ListView?
Sometimes windows defaults to Date Modified or another sorting method besides Name.
Note: I have full file paths in a List, and just file names in the ListView.
private void btnInput_Click(object sender, RoutedEventArgs e)
{
// Open Select File Window
Microsoft.Win32.OpenFileDialog selectFiles = new Microsoft.Win32.OpenFileDialog();
selectFiles.Multiselect = true;
// Process Dialog Box
Nullable<bool> result = selectFiles.ShowDialog();
if (result == true)
{
// Add Path+Filename to List
foreach (String file in selectFiles.FileNames)
{
lstFilesPaths.Add(file);
}
// Add List Filename to ListView
lsvFiles.Items.Clear();
foreach (String name in fileList)
{
lsvFileNames.Items.Add(Path.GetFileName(name));
}
}
}
The filebrowser itself won't sort its results by filename, you will need to do that before using them.
Given lstFilesPaths is a List of strings you're saving the selected file paths to for use elsewhere, try this to sort the list by file name adding:
foreach (var name in lstFilesPaths.Select(f => Path.GetFileName(f)).OrderBy(s => s))
{
lsvFileNames.Items.Add(name);
}
Or, if you'd like both your list of file paths and the list view of file names sorted, try this:
// Add Path+Filename to List
lstFilesPaths.AddRange(selectFiles.FileNames.OrderBy(f => Path.GetFileName(f)));
// Add List Filename to ListView
lsvFiles.Items.Clear();
foreach (var name in lstFilesPaths.Select(f => Path.GetFileName(f)))
{
lsvFileNames.Items.Add(name);
}
try changing to:
lstFilePaths.AddRange(selectFiles.FileNames.OrderBy(x => x))
lsvFileNames.Items.Clear();
lstFilePaths.ForEach(x => lsvFileNames.Items.Add(Path.GetFileName(x)));

ListView of recently opened files

I'm doing a text editor. How do I display a list of the last opened files in the RichTextBox in ListView? You can also click on the ListView string and open the file. Something like the history of opening files. Files are opened using Button (the code below).
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Rich Text Format | *.rtf";
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
else
{
}
}
The easiest way i have done this was store all opened files within a settings string and store all recently opened files within that string with a delimiter like \n(i use this because you cant include it in a fie name so no errors are thrown).
For example, the settings string is stored like this
"C:\my file1\nC:\myFile2\nC:\my file 3"
And when adding a new file to the list
MyApp.Properties.Settings.recents = MyApp.Properties.Settings.recents + "\n" + ofd.FileName;
MyApp.Properties.Settings.Default.Save();
you then split that and use a forloop for each occurance to generate a new listview item like this
string[] recentFiles = MyApp.Properties.Settings.recents.split('\n');
foreach (string recentItem in recentFiles) { MyListView.add(recentItem); }

Strip leading characters from a directory path in a listbox in C#

So i am attempting to teach myself C#, I have a program that I originally wrote in batch and am attempting to recreate in C# using WPF. I have a button that allows a user to set a directory, that directory selected is then displayed in a text box above a listbox which adds every subfolder, only first level, to the listbox. Now all this works fine but it writes out the entire directory path in the listbox. I have been trying to figure out how to strip the leading directory path off the list box entries for over an hour to no avail. Here is what I have so far:
private void btn_SetDirectory_Click(object sender, RoutedEventArgs e)
{
//Create a folder browser dialog and set the selected path to "steamPath"
var steamPath = new FolderBrowserDialog();
DialogResult result = steamPath.ShowDialog();
//Update the text box to reflect the selected folder path
txt_SteamDirectory.Text = steamPath.SelectedPath;
//Clear and update the list box after choosing a folder
lb_FromFolder.Items.Clear();
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f);
}
}
Now I tried changing the last line to this, and it did not work it just crashed the program:
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f.Substring(f.LastIndexOf("'\'")));
}
I am fairly certain that the LastIndexOf route is probably the right one but I am at a dead end. I apologize if this is a dumb question but this is my first attempt at using C#. Thanks in advance.
This can solve your issue
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
// string[] strArr = f.Split('\\');
lb_FromFolder.Items.Add(f.Split('\\')[f.Split('\\').Length-1]);
}
You can use this code:
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f.Remove(0,folderName.Length));
}

Combobox item preview

I have a combobox with items(paths of opened files with opendialog).
Screenshot http://screenshotuploader.com/i/01/0k8n94fka.png
How to show only files name in combobx preview?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Выбрать фаил для загрузки";
openFileDialog1.InitialDirectory = System.Environment.CurrentDirectory;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
comboBox1.Items.Add(file);
}
}
I think you need a custom class, which looks like this:
public class ComboBoxItem
{
public string Display{get;set;}
public string Value{get;set;}
public override ToString()
{
return this.Display.ToString();
}
}
Can't see how any of the other answers here would work so thought i'd help out
Just use SafeFileNames instead of FileNames,
SafeFileNames: Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path.
e.g.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFileDialog1.SafeFileNames)
{
comboBox1.Items.Add(file);
}
}
Will give you the desired result.
r u binding the combobox with the entire path..??
Just try this code to extract filename
Path.GetFileName(YourPath);
Add the resultant string to combobox

Categories