How to make OpenFileDialog variable Global? - c#

I've just recently started with C# and as a project I decided I would try and make a image converter, but I can't seem to get the variable "open" accessible in my button1 context, I'm not looking for comments on how bad my code is, I am just starting.. I just want to get this done and add on to it, I will improve the code later on, thanks. So how can I make it accessible?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button2_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
// image in picture box
pictureBox1.Image = new Bitmap(open.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
// image file path
string path = Directory.GetCurrentDirectory();
textBox1.Text = Path.GetDirectoryName(open.FileName);
}
}
public void Form1_Load(object sender, EventArgs e)
{
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
flowLayoutPanel1 = new FlowLayoutPanel();
flowLayoutPanel1.AutoSize = true;
flowLayoutPanel1.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.Controls.Add(flowLayoutPanel1);
}
public void button1_Click(object sender, EventArgs e)
{
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
if ((string)comboBox1.SelectedItem == "*.jpg")
{
pictureBox1.Image.Save(#"" + textBox1.Text + open.FileName + "", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}

You could move the variable out of the method and into the class, making it an instance field of the class. Then any method would be able to see it. However, there are a few things wrong with that approach:
The OpenFileDialog, like any modal dialog, should be disposed of when you are done with it. Storing the reference in an instance field extends its lifetime until the next time you create a new one or your form is closed, whichever comes first.
All you really need is the file name, not all the other data and resources that the OpenFileDialog carries around, so it's wasteful.
From a user experience point of view, it would be better to give the user a chance to save to a different file anyway. You would be better off presenting a SaveFileDialog to the user, initializing with the currently selected file name.
Sticking with your current UI design, the following is the right way to do what you want:
private string fileName;
public void button2_Click(object sender, EventArgs e)
{
using (OpenFileDialog open = new OpenFileDialog())
{
// image filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
// image in picture box
filename = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
// image file path
string path = Directory.GetCurrentDirectory();
textBox1.Text = Path.GetDirectoryName(open.FileName);
}
}
}
public void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(fileName))
{
return;
}
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
if ((string)comboBox1.SelectedItem == "*.jpg")
{
pictureBox1.Image.Save(#"" + textBox1.Text + fileName + "", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
Note the use of using to ensure that the OpenFileDialog instance is disposed of properly when it's no longer needed.

C# don't have global variables, but you can have a workaround for that,
public class GlobalObjects
{
private static OpenFileDialog ofd;
public static OpenFileDialog OpenFileDlg
{
get
{
if (ofd == null)
ofd = new OpenFileDialog();
return ofd;
}
}
}
and call it like,
var fileDlg = GlobalObjects.OpenFileDlg;

Related

Form ShowDialog won't load image in picture box

When I refresh my form with SHOWDIALOG my image doesn't load in my picture-box but if i refresh with only SHOW it works fine.
I want to be able to refresh with SHOWDIALOG and still have my picture load method work.
I have tried clearing data-bindings of both picture-box and the brows button.
private void formrefresh()
{
FoodItem FoodItem = new FoodItem();
FoodItem.ShowDialog();
this.Close();
}
public void GetImage()
{
OpenFileDialog BrowseImage = new OpenFileDialog();
BrowseImage.Filter = "Image Files(*.jpg; *.gif;)|*.jpg; *.gif";
if (BrowseImage.ShowDialog() == DialogResult.OK)
{
TextBox t =
Application.OpenForms["FoodItem"].Controls["imagePath"] as TextBox;
t.Text = BrowseImage.FileName;
filenametext = BrowseImage.FileName;
PictureBox p = Application.OpenForms["FoodItem"].Controls["foodImage"] as PictureBox;
p.Image = new Bitmap(BrowseImage.FileName);
}
}
private void BrowsImage_Click(object sender, EventArgs e)
{
GetFoodImage image = new GetFoodImage();
image.GetImage();
}
Finding forms (Application.OpenForms) is not a very good approach to use. Try to avoid that if possible. For example, there can be complications if there are multiple instances of a certain Form and you will have to find the exact instance you want to update.
It doesn't make much sense to use a Library to GetImage in your example. If you really need it in a separate Class Library, just return the path. Just return the image path from GetImage method and set the PictureBox from FoodImage.
private void formrefresh()
{
FoodItem foodItem = new FoodItem();
foodItem.ShowDialog();
this.Close();
}
private void BrowsImage_Click(object sender, EventArgs e)
{
GetFoodImage image = new GetFoodImage();
var imagePath = image.GetImage();
this.foodImage.Image = new Bitmap(imagePath);
this.imagePath.Text = imagePath;
}
public string GetImage(FoodItem foodItem)
{
OpenFileDialog BrowseImage = new OpenFileDialog();
BrowseImage.Filter = "Image Files(*.jpg; *.gif;)|*.jpg; *.gif";
if (BrowseImage.ShowDialog() == DialogResult.OK)
{
return BrowseImage.FileName;
}
return "";
}

how to use open file dialog?

i am trying to write a code to encrypt text using public key and decrypt using private key and passphrase.
I am not very good with programming language because i'm not a programming student. But for my mini-project, i need to write some program about encryption.
For the below code uses a text file from my c drive to encode using the public key.
But i want to use openfiledialog to choose the file instead of directing it manually(not really practical)
Really appreciate if anyone can help me edit the codes.
P.S. i don't really know how to apply openfiledialog to my code. i keep getting errors when i use informations from youtubes and google.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using DidiSoft.Pgp;
namespace TEST2
{
public partial class Form1 : Form
{
PGPLib pgp = new PGPLib();
public Form1()
{
InitializeComponent();
}
private void encryptButton_Click(object sender, EventArgs e)
{
string testingstring = pgp.EncryptString(testTextBox.Text, new FileInfo(#"c:\TCkeyPublic.txt"));
encryptedtextTextBox.Text = testingstring;
}
private void decryptButton_Click(object sender, EventArgs e)
{
try
{
String plainString = pgp.DecryptString(encryptedtextTextBox.Text,
new FileInfo(#"c:\TCkeyPrivate.txt"), passphraseTextBox.Text);
decryptedtextTextBox.Text = plainString;
encryptedtextTextBox.Text = "";
passphraseTextBox.Text = "";
}
catch
{
MessageBox.Show("ERROR! Please check passphrase and do not attempt to edit cipher text");
}
}
private void passphraseTextBox_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Assuming you're using WinForms.
Just create an instance of OpenFileDialog, call ShowDialog and if user didn't cancel the operation then read FileName property: it'll contain the full path of selected file. In code:
var dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK)
return;
new FileInfo(dlg.FileName, passphraseTextBox.Text);
Of course you may need to let user quickly filter files to display, you can use Filter property for that:
var dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
You can even allow multiple selection, set Multiselect to true and you'll get all selected files in the FileNames property:
var dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
dlg.Multiselect = true;
if (dlg.ShowDialog() != DialogResult.OK)
return;
foreach (var path in dlg.FileNames)
{
new FileInfo(path, passphraseTextBox.Text);
// ...
}
private void decryptButton_Click(object sender, EventArgs 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() == DialogResult.OK)
{
try
{
String plainString = pgp.DecryptString(encryptedtextTextBox.Text,new FileInfo(openFileDialog1.FileName), passphraseTextBox.Text);
decryptedtextTextBox.Text = plainString;
encryptedtextTextBox.Text = "";
passphraseTextBox.Text = "";
}
catch
{
MessageBox.Show("ERROR! Please check passphrase and do not attempt to edit cipher text");
}
}
}

Where is the proper place to dispose an image

I have a form with OpenFileDialog for selecting image and showing it in pictureBox. Until the form is open the user can open and then save the opened image as many times as he wants. What I want to do is, after each new selection-save, to delete the previously saved image if there is such. The problem is that as I implemented the code now I am able to delete the image the first time, if I keep on saving images with the currently open form I get an error that the resource is being used. What I do is Dispose() the image but I guess I don't do it in the right place.
This is how I open and load the image:
private void btnExplorer_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Select file";
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = fileNameFilter;
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = prefixFilter;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox1.InitialImage = new Bitmap(openFileDialog1.FileName);
pictureBox1.ImageLocation = openFileDialog1.FileName;
selectedFile = pictureBox1.ImageLocation;
selectedFileName = openFileDialog1.SafeFileName;
pictureBox1.Load();
}
catch (Exception ex)
{
logger.Error(ex.ToString());
MessageBox.Show("Error loading image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
And in the same class I have this method which I call if I need to delete an old image:
public void DeleteImage(AppConfig imagePath, string ImageName)
{
pictureBox1.InitialImage.Dispose();//Release the image before trying to delete it
string imgPath = imagePath.ConfigValue.ToString();
File.Delete(imgPath + "\\" + ImageName);
}
As you can see. The Dispose() method is here which I though will ensure that the resource will be disposed before trying to delete it but as I said this only work once and then I get the error as many times as attempts to save image I make.
P.S
The exact error I get is:
The process cannot access the file 'C:\Images\ME_083a210e1a7644198fe1ecaceb80af52.jpg' because it is being used by another process.
There is a better way to do it. Load the image using FileStream and than assign it to the pictureBox
FileStream bmp = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
Image img = new Bitmap(bmp);
pictureBox1.Image = img;
bmp.Close();
and if you want to clear the picture box, simply
pictureBox1.Image = null;
If I understand this correctly you want to remove the once "used" image from it's picture box: Set
picturebox.InitialImage=null;
(By the way: You better use picturebox.Image ...)
"Dispose" is to force the garbage collector to remove an unused object from memory.
Your error has nothing to do with the disposal of the pictureBox-image but with the lock of the source file.
Maybe it already helps if you use a "using" block for the handling of the openFileDialog.
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Select file";
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Jpeg Files(*.jpg)|*.jpg|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.InitialImage = new Bitmap(openFileDialog1.FileName);
pictureBox1.ImageLocation = openFileDialog1.FileName;
selectedFile = pictureBox1.ImageLocation;
selectedFileName = openFileDialog1.SafeFileName;
pictureBox1.Load();
}
}
public string selectedFileName { get; set; }
public string selectedFile { get; set; }
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.ImageLocation = null;
}

how to read file from open file dialog and add to URL to play using wmplib?

I am making a simple music player implementing the WMPlib to play media files ....
I am trying to open the file using a open file dialog ... the dialog comes and able to select the file but an exception comes when I try to assign the filename to Player.URL
at the line
Player.URL = openFileDialog1.FileName;
the error says
Object reference not set to an instance of an object.
Can anyone please give me a clue on how to assign the filename to the player.URL
the complete code is as follows....
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
WMPLib.WindowsMediaPlayer Player;
public Form1()
{
InitializeComponent();
}
private void PlayFile(String url)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.PlayStateChange +=
new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
Player.MediaError +=
new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
Player.URL = url;
Player.controls.play();
}
private void Player_PlayStateChange(int NewState)
{
if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
{
this.Close();
}
}
private void Player_MediaError(object pMediaObject)
{
MessageBox.Show("Cannot play media file.");
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "(mp3,wav,mp4,mov,wmv,mpg)|*.mp3;*.wav;*.mp4;*.mov;*.wmv;*.mpg|all files|*.*";
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
PlayFile(Player.URL);
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
MessageBox.Show(openFileDialog1.FileName);
Player.URL = openFileDialog1.FileName;
}
}
}
Make sure that you create an instance of WMPLib.WindowsMediaPlayer before using it. Right now it seems that you are clicking 'open file' button and trying to assign returned file name to null object.
Try to use openFileDialog1 like this:
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
Player.URL = openFileDialog1.FileName;
}
in button1_Click()

Load a bitmap image into Windows Forms using open file dialog

I need to open the bitmap image in the window form using open file dialog (I will load it from drive). The image should fit in the picture box.
Here is the code I tried:
private void button1_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog();
dialog.Title = "Open Image";
dialog.Filter = "bmp files (*.bmp)|*.bmp";
if (dialog.ShowDialog() == DialogResult.OK)
{
var PictureBox1 = new PictureBox();
PictureBox1.Image(dialog.FileName);
}
dialog.Dispose();
}
You have to create an instance of the Bitmap class, using the constructor overload that loads an image from a file on disk. As your code is written now, you're trying to use the PictureBox.Image property as if it were a method.
Change your code to look like this (also taking advantage of the using statement to ensure proper disposal, rather than manually calling the Dispose method):
private void button1_Click(object sender, EventArgs e)
{
// Wrap the creation of the OpenFileDialog instance in a using statement,
// rather than manually calling the Dispose method to ensure proper disposal
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox PictureBox1 = new PictureBox();
// Create a new Bitmap object from the picture file on disk,
// and assign that to the PictureBox.Image property
PictureBox1.Image = new Bitmap(dlg.FileName);
}
}
}
Of course, that's not going to display the image anywhere on your form because the picture box control that you've created hasn't been added to the form. You need to add the new picture box control that you've just created to the form's Controls collection using the Add method. Note the line added to the above code here:
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox PictureBox1 = new PictureBox();
PictureBox1.Image = new Bitmap(dlg.FileName);
// Add the new control to its parent's controls collection
this.Controls.Add(PictureBox1);
}
}
}
Works Fine.
Try this,
private void addImageButton_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
//For any other formats
of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG";
if (of.ShowDialog() == DialogResult.OK)
{
pictureBox1.ImageLocation = of.FileName;
}
}
You should try to:
Create the picturebox visually in form (it's easier)
Set Dock property of picturebox to Fill (if you want image to fill form)
Set SizeMode of picturebox to StretchImage
Finally:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox1.Image = Image.FromFile(dlg.Filename);
}
dlg.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == DialogResult.OK)
pictureBox1.Image = Bitmap.FromFile(open.FileName);
}
You, can also try like this, PictureBox1.Image = Image.FromFile("<your ImagePath>" or <Dialog box result>);
PictureBox.Image is a property, not a method. You can set it like this:
PictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
You can try the following:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Select file to be upload";
fDialog.Filter = "All Files|*.*";
// fDialog.Filter = "PDF Files|*.pdf";
if (fDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fDialog.FileName.ToString();
}
}
It's simple. Just add:
PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

Categories

Resources