I have code that opens the OpenFileDialog, I'm checking the size of the file to make sure it doesn't exceed specific limit.
But, if the user selected a big sized file I need to warn him and lead him back to the dialog to select a different file or click cancel.
This is what I've tried:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
while (dialog.ShowDialog() != DialogResult.Cancel)
{
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000)
{
MessageBox.Show("File size exceeded");
continue;
}
}
EDIT:
I also tried the following code but it opens the dialog each time the ShowDialog is called. So, if the user selected a file 3x the size the limit, the dialog will appear 3 times.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
dialog.FileOk += delegate(object s, CancelEventArgs ev)
{
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000)
{
XtraMessageBox.Show("File size");
dialog.ShowDialog();
}
};
if (dialog.ShowDialog() == DialogResult.OK)
{
XtraMessageBox.Show("File Selected");
}
You are half-way there, the FileOk event is what you want to use. What you are missing is setting the e.Cancel property to true. That keeps the dialog opened and avoids you having to display it over and over again. Like this:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
dialog.FileOk += delegate(object s, CancelEventArgs ev) {
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000) {
MessageBox.Show("Sorry, file is too large");
ev.Cancel = true; // <== here
}
};
if (dialog.ShowDialog() == DialogResult.OK) {
MessageBox.Show(dialog.FileName + " selected");
}
ev.Cancel = true; Check if following piece of code serves your purpose?
public void SomeMethod()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.FileOk += new CancelEventHandler(dialog_FileOk);
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
dialog.ShowDialog();
}
void dialog_FileOk(object sender, CancelEventArgs e)
{
OpenFileDialog dialog = sender as OpenFileDialog;
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000)
{
MessageBox.Show("File size exceeded");
e.Cancel = true;
}
}
Yes as far as your requirement is concern, this is OK but in general opening Dialog after showing a prompt for Size is not the best way. Instead a prompt should be displayed, best is to display the validation error on the size from the main window. And it should be User's duty to select the proper file again by opening the File Dialog again according to Usability principles of HCI.
Add a handler to FileDialog.FileOk and let verify the file size inside their.
Related
How can I set exception for image size? for instance, I am trying to select a file (image) through openfiledialogue but I want to throw an exception if the image size is less than 250x150 (assume).
public void select_image_button17_Click(object sender, EventArgs e)
{
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
AddImagesToButtons(images);
break;
}
}
}
Windows Exceptions is a class used for when the program receive errors that occur during application execution in other words it's for when the programme receive an unusual behavior , for exemple something that will make the programme 'crash' or stop working
Exeptions and validations are 2 different but similar concept
What you are looking for is a validation mechanism and there are many way to do so :
One of the thing you can do is force the image to the desired size this will avoid undesired image size :
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Size = new Size(210, 110);///--add here your desired size
AddImagesToButtons(images);
break;
}
}
}
But if you insist on displaying an error you can use a message box instead ,make a loop and when the desired size is met exit the loop , otherwise display a message Box to the user:
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
bool correctSize=false;
var imageH=null;
var imageW=null
while(!correctSize) //make a loop so only desired size will be taken
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
*ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
if(PictureBox1.Image.Size.Width==yourWidth && PictureBox1.Image.Size.height==yourHeight) //Validate size
{ correctSize =true;
AddImagesToButtons(images);
break;
}
else
MessageBox.Show("Please enter image size your desired size ")
}
}
}
OpenFileDialog is likely concerned with simply selected a file on the file system. Once you've selected, it is up to you to validate that selection meets the criteria, whatever that criteria may be. So once selection is made, and you now know path to the file, use image library to load the file, validate that file loads without issues (remember, may not be a valid file to begin with), and then validate its dimensions. If something doesn't pass, act accordingly, e.g. letting the user know why file is being rejected and suggesting picking a new one.
I have to create a button with which the user has to choose a folder.
I've try with OpenFileDialog, But there I can not select the folder and the folder just open.
This is my code:
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog";
fdlg.InitialDirectory = #"D:\dosfiles\ValPoch";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
label2.Text = fdlg.FileName;
label2.Show();
}
I try with this code, He works perfectly, But I not like the window, who opened, Is too small.
using (FolderBrowserDialog dlg = new FolderBrowserDialog())
{
dlg.Description = "Select a folder";
dlg.SelectedPath = #"D:\dosfiles\ValPoch\";
if (dlg.ShowDialog() == DialogResult.OK)
{
label2.Text = dlg.SelectedPath;
label2.ForeColor = Color.Red;
label2.Show();
}
}
How can I fix my code with OpenFileDIalog to select a folder not to open that folder ?
Thank you.
Take a look at Ookii.Dialogs, a great library in order to use common Windows dialogs including file dialogs.
I am trying to use a OpenFileDialog to let the user select a local file that can interact with my app. The file can be in use when the user selects it as I really only want to get the file's path. My issue is that if I try doing this with a OpenFileDialog, when the user presses "open", it actually tries to open the file even though I don't call for opening anywhere. Since the file is in use, it throws an error.
Is there any way for me to present a dialog for a user to just select a file an do nothing else?
Heres my current code:
DialogResult result = this.qbFilePicker.ShowDialog();
if (result == DialogResult.OK)
{
string fileName = this.qbFilePicker.FileName;
Console.WriteLine(fileName);
}
Make sure you are using
using System.Windows.Forms;
Then the following code from MSDN will not open your file unless you explicitly uncomment the bit that opens the file :)
(Take out the bits that don't pertain to you such as the .txt filter etc)
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileName = openFileDialog1.FileName;
Console.WriteLine(fileName);
//to open the file
/*
try
{
Stream myStream = null;
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
* */
}
}
I have a TextBox named textbox1 and a Button named button1.
When I click on button1 I want to browse my files to search only for image files (type jpg, png, bmp...).
And when I select an image file and click Ok in the file dialog I want the file directory to be written in the textbox1.text like this:
textbox1.Text = "C:\myfolder\myimage.jpg"
Something like that should be what you need
private void button1_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".png";
dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
textBox1.Text = filename;
}
}
var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"};
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later.
Can anybody tell me how to obtain the file path from the save dialog box to use it later?
Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 1;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Console.WriteLine(saveFileDialog1.FileName);//Do what you want here
}
Addressing the textbox...
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = saveFileDialog.FileName;
}
private void mnuFileSave_Click(object sender, EventArgs e)
{
dlgFileSave.Filter = "RTF Files|*.rtf|"+"Text files (*.txt)|*.txt|All files (*.*)|*.*";
dlgFileSave.FilterIndex = 1;
if (dlgFileSave.ShowDialog() == System.Windows.Forms.DialogResult.OK && dlgFileSave.FileName.Length > 0)
{
foreach (string strFile in dlgFileSave.FileNames)
{
SingleDocument document = new SingleDocument();
document.rtbNotice.SaveFile(strFile, RichTextBoxStreamType.RichText);
document.MdiParent = this;
document.Show();
}
}
}
Try below code.
saveFileDialog1.ShowDialog();
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);