OpenFileDialog cuts off pre-populated file name [duplicate] - c#

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();

Related

C# OpenFileDialog/CommonOpenFileDialog

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);

Why does openfiledialog say 'Path does not exist' or 'Catastrophic Error' after selecting a file for the second time?

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.

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); }

How to detect whether pictureBox successfully displayed the image or not?

I have a pictureBox that loads an image directly from the internet. The image can change dynamically and is specified by the user in a textBox that has a TextChanged event that changes the image in pictureBox to the URL in the textBox. When user clicks the submit button, the image URL is saved in the database. But before saving I want to validate the image, that whether the image displayed successfully or the error image is displayed in place of it. So how can I validate this?
You can use the LoadComplete event to see when it has changed, and if the eventArg's error is null (successful) or not null (fail).
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show(e.Error.ToString());
}
this.pictureBox1.Validated += new EventHandler(pictureBox1_Validated);
this.pictureBox1.ImageLocation = this.textBox1.Text;
-
Edit: Just saw Dips' comment, did not use that link but is same means to answer this.
Place the code below in the function where you are retrieving the path of image from textBox ,be sure to place it before you do anything else on that path;
string path = "Path to image";
Bitmap bmp;//To validate the Image.
try
{
bmp = new Bitmap(path);//Create a Bitmap object from the given path.
if (bmp != null)
{
pictureBox1.Load(path);//Display the image to the user.
//Now it's safe to store the image path in the database,
//because we have validated it.
bmp.Dispose();//Dispose the Bitmap object to free occupied resources.
//Place you database related code here which uses the path we just validated.
}
}
catch (ArgumentException)
{
MessageBox.Show("The specified image file is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
catch (FileNotFoundException)
{
MessageBox.Show("The path to image is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
When you've done this you can place your code where I've shown the comment //Place your database....This ensures that the file path and image is validated before anything else uses them.`This method also checks if the image file is actually an image and not a .txt or .exe with its extension changed to .jpg or any other image format,as you've mentioned in your comments you need to check if the path actually points to an image file.
You can the extend the exception handling mechanism if you need something more than displaying a MessageBox with error information.One more thing that is worth to be mentioned is that,before you display any image or do anything you will have to check if the url is valid one,to simplify this step you can try to download the file(it can be anything - an image,an executable,a text file or at least a web page,when it has been downloaded pass the path to that file(relative to filesystem) to this function.
Hope it works for you.
Suppose Pic1 is name of your control. To validate then you can use simply,
if(pic1.ImageLocation.Trim().Length>4) // > 4 since a shortest valid image
file will be a.png or something
similar; length= 5
{
if(validExtensions(pic1.ImageLocation)
{
//then put the path to database
}
}
Updated
//Mehod to valid image extensions
private bool validExtensions(string url)
{
var imgs = new []{".jpg",".gif",".png",".bmp",".jpeg"};
var ext = System.IO.Path.GetFileExtention(url); // see the correct method
in intellisense
if(imgs.Contains(ext)
return false;
}
Update 2
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
dialog.InitialDirectory = #"C:\";
dialog.Title = "Please select an image file to encrypt.";
if (dialog.ShowDialog() == DialogResult.OK)
{
//Encrypt the selected file. I'll do this later. :)
}

Change file extension when user changes Save As Type in SaveFileDialog

I have a SaveFileDialog with the option of saving with type .foo or .bar. The first item in the list, and selected by default, is .foo. The default filename is "untitled", and the default extension is ".foo". When the SaveFileDialog appears, it puts "untitled" in the file name textbox. I can change it to "untitled.foo" but it still doesn't change the behavior in regards to my problem:
If the user switches to .bar, how can I make the filename change to untitled.bar? There's only two events, neither of which is the one I want, and it doesn't seem to be changing itself.
Ed,
I just tested and it works just fine.
I did this:
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled";
sfd.Filter = "Text (*.txt)|*.txt|Word Doc (*.doc)|*.doc";
sfd.ShowDialog();
And it automatically changes the suggested save name depending on the filter I choose.
I used the .NET 2.0 framework.
But I'm on Windows 7, which I think matters, since you see the system's file-save dialog, and the way it's implemented is what matters here.
Adding DefaultExt and AddExtension will give you the behaviour you're looking for. Simialr to question/answer provided here:
https://stackoverflow.com/a/1213353/101971
var saveFileDialog = new SaveFileDialog
{
Filter = "Foo (*.foo)|*.foo|Bar (*.bar)|*.bar",
DefaultExt = "foo",
AddExtension = true
};
When you go to actually save the file you can get the file name from the dialog box, then perform the necessary string manipulation from there. The file name is a member of the instance of the SaveFileDialog
You may do:
savefiledialog1.AddExtension = True
//Drag a SaveFileDialog from toolbox, and then...
//Create a button.... let's say this is my button named button1
private void button1_Click(object sender, EventArgs e)
{
//saveFileDialog1 is the tool you grabbed from toolbox and could be renamed if you want
//using Filter.. so user will see the extension has been selected by default
saveFileDialog1.Filter = "Text Document(.txt)|.txt";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
/*saveFileDialog1.Filter = "Text Document(.txt)|.txt";*/
File.Create(saveFileDialog1.FileName);
MessageBox.Show("New file created succesfully!");
} else {
MessageBox.Show("Unsuccessful!");
}
}

Categories