I am working on this piece of code that is supposed to open a file dialog and put them into a textbox.
The error is that every time I select more than 1 file while running the app, I get an error in the textbox. If I select only one file, it works fine.
The code is this
private void filePickerButton_Click(object sender, RoutedEventArgs e)
{
// Create the OpenFileDialog object
OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.Multiselect = true;
// Check to see if we have a result
if (dialog.ShowDialog() == true)
{
filePickerTextBox.Text = dialog.FileNames.ToString();
}
else
{
outputTextBox.Text = "Operation cancelled." + "\n" + outputTextBox.Text;
}
}
I am switching between dialog.Filename.ToString(); (to select one file) and dialog.Filenames.ToString(); to select multiple. When using the latter and selecting a file (whether its only one, or more that one, doesn't matter) the my text box shows System.String[]
Anyone know how to fix this?
Thx!
when you are selecting multiple files you get a array of files, as your textbox says: System.String[]
you could use:
filePickerTextBox.Text = string.join(",", dialog.FileNames);
Related
I am trying to make a file display. When the user selects a file, it displays the icon of the file in the window. When I select the Google Chrome icon and click on 'OK' in the openfiledialog, the intended result happens. (see pictures below)
However, when I select another icon (e.g Word), it gives me the error 'Path does not exist'.
(see pictures below)
If I select another file (e.g File Explorer) it gives me 'Catastrophic Error' (see pictures below)
For some reason, this problem only happens with shortcut files. For other files like .txt files or .exe files, this problem does not occur.
Here is my code (Add_Item is the name of the button)
private void AddItem_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
foreach (String myfile in openFileDialog.FileNames)
{
// here myfile represent your selected file name
//get filename
string filename = System.IO.Path.GetFileName(myfile);
//TODO: Create settings
Icon icon1 = System.Drawing.Icon.ExtractAssociatedIcon(myfile);
Bitmap icon = icon1.ToBitmap();
System.Windows.Controls.Image image = new System.Windows.Controls.Image();
image.Source = BitmapToImageSource(icon);
Tiles.Children.Add(image);
}
}
}
Can anyone help me?
Thanks
Alright, {DeferenceLinks = false} fixed my problem.
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.
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); }
This question already has answers here:
Default name with OpenFileDialog C#?
(3 answers)
Closed 1 year ago.
I use the following to display an Open File dialog:
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.FileName = Properties.Settings.Default.Last_competition_file;
fdlg.Filter = "FS database files (*.fsdb)|*.fsdb|All files (*.*)|*.*";
fdlg.FilterIndex = 0;
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
(Properties.Settings.Default.Last_competition_file contains the whole path to the last file)
Problem: For a file name "c:\data\nationals_2014.fsdb", the File name field only shows "ionals_2014.fsdb".
When clicking into the File name field, and moving the cursor to the left, the remainder of the file name & path re-appears. But I'm looking for a way to make the whole file name visible from the beginning.
Note that this is not a length issue. I also tried setting path and file name separately (through OpenFileDialog.InitialDirectory), but even then only the tail end of the (now much shorter) file name was displayed.
Any ideas how to get the Open File dialog to show the full pre-populated file name from the beginning?
Caveat: This is a Kludge, not a real answer.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.FileName = Properties.Settings.Default.Last_competition_file;
fdlg.Filter = "FS database files (*.fsdb)|*.fsdb|All files (*.*)|*.*";
fdlg.FilterIndex = 0;
fdlg.ShowHelp = true;
fdlg.HelpRequest += new System.EventHandler(HelpRequested); ;
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
private void HelpRequested(object sender, EventArgs e)
{
MessageBox.Show(".. is no Help", "There..");
}
The style of the Dialog reverts to an older incarnation.
Shrug. Some workarounds make me wonder about many things..
I got the same thing on windows 10 with an open file dialog set up like this:
var dialog = new OpenFileDialog{
Filter = "excel files (*.xlsx)|*.xlsx",
InitialDirectory = #"c:\temp",
FileName = #"MyFileNameExceeds14Characters.xlsx"
};
dialog.ShowDialog();
Work-arounds:
Set AutoUpgradeEnabled = false to revert to an older dialog style. But then you're stuck with the older UI.
Make sure the file name is under 14 characters long. If you don't have direct control of the file name, then run it through Path.GetFileNameWithoutExtension() to slim it down as much as possible.
Use a SaveFileDialog instead, which does not have this issue.
Inserting code:
SendKeys.Send("{HOME}");
before the line :
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
does the job.
Found a good answer on another thread:
c# Sending keyboard commands to another window / process
This does a good job of fixing the file name display.
I use a timer anyway in order to make sure that dialog is centered on active screen. Once the dialog is displayed:
IntPtr handle = FindWindowByCaption(IntPtr.Zero, dialogTitle));
SetForegroundWindow(handle);
SendKeys.SendWait("{HOME}");
SendKeys.Flush();
Background: I'm developing a WinForms application using C# with an OpenFileDialog and FileBrowserDialog that is supposed to:
Enable selection of multiple xls files.
After selection is made, Display selected xlsx filenames in textbox
Copy the selected files to a separate directory Consolidated
Show results in logging window on the bottom of the winForm App
How do you recommend to fix any of the following Errors in Debugging:
After selecting the files from the FileBrowserDialog, another FileBrowserDialog box comes up
Only 1 of the files selected shows up in the textbox. There's not enough room to display all files b/c the file paths are so long. Would it be possible to just display the filename without the full path? Is there a better way for confirming the MultiSelect worked in a WinForm besides displaying the selected files in a textbox that you recommend?
Hitting the Consolidate button does not copy the selected files to the consolidated directory or display the correct log files.
I get the following in the Logging Window: "Source Files: System.String[]"
Here's my code:
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFilesList = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
{
using (myStream)
{
Log("Source Files: " + sourceFilesList.FileNames);
}
} // ends if
} // ends try
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
} // ends if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
} // ends public void sourceFiles_Click
private void consolidateButton_Execute_Click(object sender, EventArgs e)
{
string consolidatedFolder = targetFolderBrowserDialog.SelectedPath;
foreach (String file in sourceFileOpenFileDialog.FileNames)
{
try
{
// Copy each selected xlsx files into the specified TargetFolder
System.IO.File.Copy(sourceFileOpenFileDialog.FileName, consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
Log("File" + sourceFileOpenFileDialog.FileName + " has been copied to " + consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
}
} // ends foreach loop
} // ends void consolidateButton_Execute_Click
I will give +1 up-votes for any helpful answers!
Thanks for looking!
Update: Updated code w/ a foreach (string FileName in sourceFilesList.FileNames) loop and a listbox control, still having problems w/ filebrowser loading 2x, and the "Source Files: System.String[]" message
Your code snippet doesn't match your question very well, there's no sign of you displaying the FolderBrowserDialog. There is an obvious mistake in the File.Copy() call, you pass sourceFileOpenFileDialog.FileName instead of file.
Check this answer for a way to display path names in a limited amount of space:
using System;
using System.ComponentModel;
using System.Windows.Forms;
class PathLabel : Label
{
[Browsable(false)]
public override bool AutoSize
{
get { return base.AutoSize; }
set { base.AutoSize = false; }
}
protected override void OnPaint(PaintEventArgs e)
{
TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.PathEllipsis;
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, flags);
}
}
To get only file name from file path use Path.GetFileName(...).
To check if multiple files were selected, you can just check openFileDialog.FileNames Length property - it's an array.
Fixed Logging Window Message: "Source Files: System.String[]" by adding:
foreach (string FileName in sourceFilesList.FileNames)
{
sourceFilesList.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFilesList.FileNames[i]);
i++;
}
// under if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
Fixed 2 FileBrowserDialog boxes coming up when Selecting files by:
if ((myStream = sourceFilesList.OpenFile()) != null)
// deleted duplicate line