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.
Related
i'm sorry if i'm going to cause some confusion with the question, as to it referring to something that might not be possible, but i'd like to, using winforms, create a form that would allow the user to load an image, select from the combobox some certificate level, then place its associated stamp over said image...
the issue i ran into is this: the loading works just fine, the selecting from the combobox (as i even know how to get specific images (let's call them 'stamps') from specific locations, and place them into a picturebox), and i can even save the first loaded image (let's call it 'pic1' for reference)... but i don't know how to program whatever it would be to place the 'stamps' over the 'pic1'... hell i could barely code the lines needed to what i already did, except for the formatting, and wouldn't have done it without help from 'stackoverflow'...
truth be told, i just recently finished some crappy 200 hours of coding in c# (and they weren't learned online, it was actually part of a course -_-...)
any ideas, help, suggestions or even a 'go back to what you were doing before starting to mess with programming', please?
thank you in advance. i'll leave here what i already have...
p.s.: i don't have much experience with OOP either, that's why the code below won't look like anything really optimized... :s
btw, the strings below inside the message boxes are in portuguese, because the user is my father, and it'd be easier for him, here in portugal, to have the form working in portuguese...
oh, and if you know any other language in which i should perhaps do this, please give that as feedback... many thanks :)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// format form
// TopMost gets the window at max resolution size; WindowsState already maximizes window at start;
this.TopMost = true;
this.WindowState = FormWindowState.Maximized;
// format panel
panPic.AutoSize = false;
panPic.AutoScroll = true;
// format picbox
pbPic.SizeMode = PictureBoxSizeMode.AutoSize;
pbPic.Location = new Point(0, 0);
}
private void btLoad_Click(object sender, EventArgs e)
{
// boolean tester
bool test = false;
// turn combobox and apply btn enabled;
cbxCertificate.Enabled = true;
btApply.Enabled = true;
do
{
// open dialog box to upload picture;
// instance OpenFileDialog class object 'dlg';
OpenFileDialog dlgPic = new OpenFileDialog();
// define object dialog title;
dlgPic.Title = "Por favor selecione imagem a carregar";
// define object dialog filter;
dlgPic.Filter = "All Files|*.*";
// if user decides object and presses 'OK';
if (dlgPic.ShowDialog() == DialogResult.OK)
{
// check if continue (probability of uploading incorrect image)
DialogResult dlgConf = MessageBox.Show("Carregou a imagem: "
+ dlgPic.SafeFileName.ToString() + "\nContinuar?", "Continuar", MessageBoxButtons.YesNo);
if (dlgConf == DialogResult.Yes)
{
// show image and its location
txbLocation.Text = dlgPic.FileName.ToString();
pbPic.Image = Image.FromFile(dlgPic.FileName);
// check tester true to exit cycle
test = true;
break;
}
else
{
// keep tester at false to continue inside the cycle;
test = false;
continue;
}
}
else
{
break;
}
} while (test == false);
}
private void btApply_Click(object sender, EventArgs e)
{
if (cbxCertificate.SelectedItem != null)
{
switch (cbxCertificate.SelectedText)
{
case "A+":
// image location
// "Parent_Directory"\Certificados\cer_a_mais.png
break;
case "A":
// image location
// "Parent_Directory"\Certificados\cer_a.png
break;
case "B":
// image location
// "Parent_Directory"\Certificados\cer_b.png
break;
case "B-":
// image location
// "Parent_Directory"\Certificados\cer_b_menos.png
break;
case "C":
// image location
// "Parent_Directory"\Certificados\cer_c.png
break;
case "D":
// image location
// "Parent_Directory"\Certificados\cer_d.png
break;
case "E":
// image location
// "Parent_Directory"\Certificados\cer_e.png
break;
case "F":
// image location
// "Parent_Directory"\Certificados\cer_f.png
break;
}// switch
// enable save image btn
btSave.Enabled = true;
}
else
{
MessageBox.Show("Por favor selecione primeiro o tipo de certificado pretendido.");
}
}
private void btSave_Click(object sender, EventArgs e)
{
// confirm saving before actually opening the save dialog box
DialogResult dlgConf = MessageBox.Show("Vai guardar a imagem editada. Continuar?", "Confirmar", MessageBoxButtons.YesNo);
// observe validation
if (dlgConf == DialogResult.Yes)
{
// save image from picture box to selected folder
// instance save file dialog
SaveFileDialog save = new SaveFileDialog();
// default file name
save.FileName = "EditedImage";
// default file type
save.DefaultExt = ".jpg";
// default filter
save.Filter = "Image (.jpg)|*.jpg";
// restore current directory in case of closing before correct saving
save.RestoreDirectory = true;
// save file
if (save.ShowDialog() == DialogResult.OK)
{
string fileName = save.FileName;
// define the using statement in case the object goes out of scope
using (System.IO.FileStream fstream = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
{
// define image saving ext and save object image into stream file selected path
pbPic.Image.Save(fstream, System.Drawing.Imaging.ImageFormat.Jpeg);
// close stream
fstream.Close();
}
}// if2
}// if1
else
{
MessageBox.Show("Continue a edição por favor...");
}// else1
}
}// class Form
//// AFTER THE SITUATION WAS SOLVED ////
public partial class Form1 : Form
{
#region constructor
public Form1()
{
InitializeComponent();
// format form
// TopMost gets the window at max resolution size; WindowsState already maximizes window at start;
this.TopMost = true;
this.WindowState = FormWindowState.Maximized;
// format panel
panPic.AutoSize = false;
panPic.AutoScroll = true;
// format picbox
pbPic.SizeMode = PictureBoxSizeMode.AutoSize;
pbPic.Location = new Point(0, 0);
}
#endregion
#region load_pic
private void btLoad_Click(object sender, EventArgs e)
{
// boolean tester
bool test = false;
// turn combobox and apply btn enabled;
cbxCertificate.Enabled = true;
btApply.Enabled = true;
do
{
// open dialog box to upload picture;
// instance OpenFileDialog class object 'dlg';
OpenFileDialog dlgPic = new OpenFileDialog();
// define object dialog title;
dlgPic.Title = "Por favor selecione imagem a carregar";
// define object dialog filter;
dlgPic.Filter = "All Files|*.*";
// if user decides object and presses 'OK';
if (dlgPic.ShowDialog() == DialogResult.OK)
{
// check if continue (probability of uploading incorrect image)
DialogResult dlgConf = MessageBox.Show("Carregou a imagem: "
+ dlgPic.SafeFileName.ToString() + "\nContinuar?", "Continuar", MessageBoxButtons.YesNo);
if (dlgConf == DialogResult.Yes)
{
// show image and its location
txbLocation.Text = dlgPic.FileName.ToString();
pbPic.Image = Image.FromFile(dlgPic.FileName);
// check tester true to exit cycle
test = true;
break;
}
else
{
// keep tester at false to continue inside the cycle;
test = false;
continue;
}
}
else
{
break;
}
} while (test == false);
}
#endregion
#region apply_stamp
private void btApply_Click(object sender, EventArgs e)
{
// parent directory
// original image to execute the method 'addStamp';
// bitmap image to use in the method 'addStamp';
// string to include the path of the stamp,
// to be changed according to each case below (see switch);
string parentDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
Image originalImage;
Bitmap bitmap;
string stampDir = "";
if (cbxCertificate.SelectedItem != null)
{
// switch
switch (cbxCertificate.SelectedItem.ToString())
// note: whenever i need to switch over what's selected on a combobox,
// use 'SelectedItem.ToString()';
{
case "A+":
stampDir = parentDir + "\\Certificados\\cer_a_mais.png";
break;
case "A":
stampDir = parentDir + "\\Certificados\\cer_a.png";
break;
case "B":
stampDir = parentDir + "\\Certificados\\cer_b.png";
break;
case "B-":
stampDir = parentDir + "\\Certificados\\cer_b_menos.png";
break;
case "C":
stampDir = parentDir + "\\Certificados\\cer_c.png";
break;
case "D":
stampDir = parentDir + "\\Certificados\\cer_d.png";
break;
case "E":
stampDir = parentDir + "\\Certificados\\cer_e.png";
break;
case "F":
stampDir = parentDir + "\\Certificados\\Certificados\\cer_f.png";
break;
}// switch
// declare the originalImage being the image from the picture box (previously loaded);
// execute the addStamp();
// replace the image on the picture box with the edited one (bitmap);
originalImage = pbPic.Image;
bitmap = addStamp(originalImage, stampDir);
pbPic.Image = bitmap;
// enable save image btn
btSave.Enabled = true;
}
else
{
MessageBox.Show("Por favor selecione primeiro o tipo de certificado pretendido.");
}
}
#endregion
#region save_pic
private void btSave_Click(object sender, EventArgs e)
{
// confirm saving before actually opening the save dialog box
DialogResult dlgConf = MessageBox.Show("Vai guardar a imagem editada. Continuar?", "Confirmar", MessageBoxButtons.YesNo);
// observe validation
if (dlgConf == DialogResult.Yes)
{
// save image from picture box to selected folder
// instance save file dialog
SaveFileDialog save = new SaveFileDialog();
// default file name
save.FileName = "EditedImage";
// default file type
save.DefaultExt = ".jpg";
// default filter
save.Filter = "Image (.jpg)|*.jpg";
// restore current directory in case of closing before correct saving
save.RestoreDirectory = true;
// save file
if (save.ShowDialog() == DialogResult.OK)
{
string fileName = save.FileName;
// define the using statement in case the object goes out of scope
using (System.IO.FileStream fstream = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
{
// define image saving ext and save object image into stream file selected path
pbPic.Image.Save(fstream, System.Drawing.Imaging.ImageFormat.Jpeg);
// close stream
fstream.Close();
}
}// if2
}// if1
else
{
MessageBox.Show("Continue a edição por favor...");
}// else1
}
#endregion
#region methods
public Bitmap addStamp(Image originalImage, String stampImagePath)
{
Image stampImage = Image.FromFile(stampImagePath);
Bitmap bitmap = new Bitmap(originalImage);
Graphics gr = Graphics.FromImage(bitmap);
gr.DrawImage(stampImage, new Point(0, 0));
return bitmap;
}
#endregion
}// class Form
thank you again to those who helped :)
Check this out, the code is very well documented, should not be so hard to understand it, you could try a step by step debug:
http://www.codeproject.com/Articles/2927/Creating-a-Watermarked-Photograph-with-GDI-for-NET
As suggested by comments I wrote a little method which may help you:
public void addStamp(String originalImagePath, String stampImagePath,String outputPath)
{
Image originalImage=Image.FromFile(originalImagePath);
Image stampImage = Image.FromFile(stampImagePath);
Bitmap bitmap = new Bitmap(originalImage);
Graphics gr = Graphics.FromImage(bitmap);
gr.DrawImage(stampImage, new Point(0, 0));
bitmap.Save(outputPath, System.Drawing.Imaging.ImageFormat.Png);
}
I have collected a code in c# for browsing files and folders in windows. My sample code segment is as follows:
void ButtonbrowseOnClick(object obj, EventArgs ea)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
But, I am getting the following error:
The name 'openFileDialog1' does not exist in the current context
What's wrong in the code segment?
It does not exist cause it hasn't been defined.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
Are you sure you have defined the openFileDialog1? Changing the second line of your method to the bellow, seems to solve the problem
void ButtonbrowseOnClick(object obj, EventArgs ea)
{
int size = -1;
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //define the variable
DialogResult result = openFileDialog1.ShowDialog();
//your code
I am selecting file from openfiledialoge and displaying it in picturebox and its name in textbox when I click on delete button I am getting exception The process cannot access the file because it is being used by another process.
I searched a lot for this exception to get resolved but i didn't fine any of them working, when i tried closing file with imagename which is in textbox i.e the file i am displaying in picturebox ; using IsFileLocked method,this closes and deletes all files of particular directory path ,but how can I delete the only file shown in picturebox,where I am going wrong
public partial class RemoveAds : Form
{
OpenFileDialog ofd = null;
string path = #"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking.
public RemoveAds()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
ofd = new OpenFileDialog();
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
}
}
else
{
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
//Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
if (Directory.Exists(path))
{
var directory = new DirectoryInfo(path);
foreach (FileInfo file in directory.GetFiles())
{ if(!IsFileLocked(file))
file.Delete();
}
}
}
public static Boolean IsFileLocked(FileInfo path)
{
FileStream stream = null;
try
{ //Don't change FileAccess to ReadWrite,
//because if a file is in readOnly, it fails.
stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None );
}
catch (IOException)
{ //the file is unavailable because it is:
//still being written to or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
}
Thanks in advance for any help
The (previously) accepted answer to this question is very poor practice. If you read the documentation on System.Drawing.Bitmap, in particular for the overload that creates a bitmap from a file, you will find :
The file remains locked until the Bitmap is disposed.
in your code you create the bitmap and store it in a local variable but you never dispose of it when you are done. This means your image object has gone out of scope but has not released its lock on the image file you are trying to delete. For all objects that implement IDisposable (like Bitmap) you must dispose of them yourself. See this question for example (or search for others - this is a very important concept!).
To correct the problem properly you simply need to dispose of the image when you are done with it :
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName); // create the bitmap
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose(); // dispose the bitmap object
}
Please do not take the advice in the answer below - you should nearly never need to call GC.Collect and if you need to do it to make things work it should be a very strong signal that you are doing something else wrong.
Also, if you only want to delete the one file (the bitmap you have displayed) your deletion code is wrong and will delete every file in the directory as well (this is just repeating Adel's point). Further, rather than keep a global OpenFileDialog object alive simply to store the file name, I would suggest getting rid of that and saving just the file info :
FileInfo imageFileinfo; //add this
//OpenFileDialog ofd = null; Get rid of this
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
OpenFileDialog ofd = new OpenFileDialog(); //make ofd local
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
imageFileinfo = new FileInfo(ofd.FileName); // save the file name
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose();
}
ofd.Dispose(); //don't forget to dispose it!
}
else
{
return;
}
}
Then in your second button handler you can just delete the one file you are interested in.
private void button2_Click(object sender, EventArgs e)
{
if (!IsFileLocked(imageFileinfo))
{
imageFileinfo.Delete();
}
}
I had the same problem : I loaded a file in a PictureBox and when trying to delete it I got the same exception.
This occurred only when the image was displayed.
I tried them all :
picSelectedPicture.Image.Dispose();
picSelectedPicture.Image = null;
picSelectedPicture.ImageLocation = null;
and still got the same exception.
Then I found this on CodeProject : [c#] delete image which is opened in picturebox.
Instead of using PictureBox.Load() it creates an Image from the file and sets it as PictureBox.Image:
...
// Create image from file and display it in the PictureBox
Image image = GetCopyImage(imagePath);
picSelectedPicture.Image = image;
...
private Image GetCopyImage(string path) {
using (Image image = Image.FromFile(path)) {
Bitmap bitmap = new Bitmap(image);
return bitmap;
}
}
No more exceptions when I delete the file.
IMHO, this is the most suitable solution.
EDIT
I forgot to mention that you can safely delete the file immediately after display :
...
// Create image from file and display it in the PictureBox
Image image = GetCopyImage(imagePath);
picSelectedPicture.Image = image;
System.IO.File.Delete(imagePath);
...
use this code
string imgName = ofd.SafeFileName;
if (Directory.Exists(path))
{
var directory = new DirectoryInfo(path);
foreach (FileInfo file in directory.GetFiles())
{
GC.Collect();
GC.WaitForPendingFinalizers();
file.Delete();
}
}
Your button2_Click event handler is cycling through all the files inside your directory & doing the deletes.
You need to change your code like the following:
public partial class RemoveAds : Form
{
OpenFileDialog ofd = null;
string path = #"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking.
string fullFilePath;
public RemoveAds()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
ofd = new OpenFileDialog();
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
fullFilePath = ofd.FilePath;
ofd.RestoreDirectory = true;
}
}
else
{
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
FileInfo file = new FileInfo(fullFilePath);
if(!IsFileLocked(file))
file.Delete();
}
}
public static Boolean IsFileLocked(FileInfo path)
{
FileStream stream = null;
try
{ //Don't change FileAccess to ReadWrite,
//because if a file is in readOnly, it fails.
stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None );
}
catch (IOException)
{ //the file is unavailable because it is:
//still being written to or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
}
By using GetThumnailImage you have to specify the width and height which is static.
Use the Load method instead.
eg: pictureBox1.Load(Path to the image); by using this u will have no problem in deleting the image or the folder before closing the app. no other methods need to be created.
hope this helps
I'm trying to use openFileDialog to open a Bitmap image and place it on my form. My form construtor...
public Form1()
{
InitializeComponent();
drawing = new Bitmap(drawingPanel.Width, drawingPanel.Height, drawingPanel.CreateGraphics());
Graphics.FromImage(drawing).Clear(Color.White);
// set default value for line thickness
tbThickness.Text = "5";
}
... opens a new form with a blank screen, and I can draw on it using the mouse and various color selector buttons. I then save the file with this method:
private void btnSave_Click(object sender, EventArgs e)
{
// save drawing
if (file == null) // file is a FileInfo object that I want to use
// to check to see if the file already exists
// I haven't worked that out yet
{
drawing.Save("test.bmp");
//SaveBitmap saveForm = new SaveBitmap();
//saveForm.Show();
}
else
{
drawing.Save(fi.FullName);
}
}
The image does save to the debug folder as a .bmp file. Then I use OpenFileDialog to open the file:
private void btnOpen_Click(object sender, EventArgs e)
{
FileStream myStream;
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "bmp files (*.bmp)|*.bmp";
if (openFile.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = (FileStream)openFile.OpenFile()) != null)
{
using (myStream)
{
PictureBox picBox = new PictureBox();
picBox.Location = drawingPanel.Location;
picBox.Size = drawingPanel.Size;
picBox.Image = new Bitmap(openFile.FileName);
this.Controls.Add(picBox);
}
}
}
catch (Exception ex)
{
}
}
}
What happes is that OpenFileDialog box comes up. When I select the file test.bmp, the screen goes away and then reappears, when I select it again, the OpenFileDialog window goes away and I'm back to my form with no image. Was hoping for some pointers. No compile or runtime errors.
Why are you calling ShowDialog() twice?
Just call ShowDialog once, so it doesn't open twice, like you indicated.
From MSDN:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "bmp files (*.bmp)|*.bmp";
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
PictureBox picBox = new PictureBox();
picBox.Location = drawingPanel.Location;
picBox.Size = drawingPanel.Size;
picBox.Image = new Bitmap (myStream);
this.Controls.Add(picBox);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
You open a dialog panel, then when it closes you check to see if the result was OK; then you open another new dialog in the using block; then you assign the image result of that to the PictureBox, and then throw everything away when the using block disposes.
You're calling ShowDialogue twice which is likely the source of your problem. Just use the following code, remove everything else from the method. Your use of using is also incorrect. it does clean up which is disposing of the results. You need to refactor or remove the using statement.
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog()
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox picBox = new PictureBox();
picBox.Location = drawingPanel.Location;
picBox.Size = drawingPanel.Size;
picBox.Image = new Bitmap (dlg.FileName);
this.Controls.Add(picBox);
}
}
}
The code above works but is without clean up or error handling. I'll leave that to you.
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.