Trying to get filepath through Openfiledialogue - c#

I am writing code for button click on which using filedialogue the file opens and i am able to choose picture from it. then i want to extract the path of the file and store it in a string variable and pass that as argument ( here compiler throws exception: "A first chance exception of type 'System.IO.FileNotFoundException' occurred in System.Drawing.dll,Additional information: OK" ), as for my code i need the path dynamically so that everytime similar picture doesn't showup ..
//choose image from file
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";
string a = "";
a = openFileDialog1.ShowDialog().ToString();
string directoryPath = Path.GetDirectoryName(a);
Image ToBeCropped = Image.FromFile(a,true);//exception
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
AddImagesToButtons(images);
}
}

The FileName property will be set when the dialog returns with an OK status.
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
// User cancelled out of dialog
}
else
{
string filename = openFileDialog1.FileName;
}

Related

C# Copying Multiple Files Gives 'Could not find a part of the path' Error, Win Forms App

I'm trying to copy the contents of a folder into another folder using OpenFileDialog, but when I click ok it gives me 'Could not find a part of the path' even though I declared the destination path. This is my code
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int index = e.RowIndex;
DataGridViewRow data = dataGridView1.Rows[index];
selected = data.Cells[0].Value.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
string strDestinationFolder = #"C:\Users\Ara\source\repos\WindowsFormsApp3\WindowsFormsApp3\bin\Debug\pics\"+selected;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
foreach (string fileName in ofd.FileNames)
{
File.Copy(fileName, strDestinationFolder + #"\" + Path.GetFileName(fileName));
}
}
the Selected variable gets it's value from a the selected row in a datagridview then I concatenate it with the destination folder(pics) path knowing that there is a directory that it's name corresponds with the selected variable in the (pics) folder, but when I hardcode the path like this
string strDestinationFolder = #"C:\Users\Ara\source\repos\WindowsFormsApp3\WindowsFormsApp3\bin\Debug\pics\abc";
it works. How can I get the destination folder when I click datagridview row? Thanks.
It looks like your "pics" folder exists, but you never create a sub-folder named whatever selected is. So, when you try ...\pics\abc, it works because it's putting abc in pics (which exists).
If selected is test and your filename is abc, then strDestinationFolder + #"\" + Path.GetFileName(fileName)); is actually ...\pics\test\abc. Since you never create the sub-folder with the name: selected (this example: test), it doesn't find it. So...
Try creating the sub-folder before the copy:
string strDestinationFolder = #"C:\Users\Ara\source\repos\WindowsFormsApp3\WindowsFormsApp3\bin\Debug\pics\"+selected;
// CREATE selected SUB-FOLDER
if(!Directory.Exists(strDestinationFolder))
Directory.Create(strDestinationFolder);
// YOUR EXISTING CODE BELOW
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
foreach (string fileName in ofd.FileNames)
{
File.Copy(fileName, strDestinationFolder + #"\" + Path.GetFileName(fileName));
}
}

Trying to save file without using SaveFileDialog

I am creating a text editor and i am stuck on the SaveFileDialog window opening
and asking to overwrite the current file open.
I have seen all the similar questions asked like this on SO but none have been able to help me. I have even tried the code from this question: "Saving file without dialog" Saving file without dialog
I got stuck on my program having a problem with FileName.
Here is the code i have currently
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(save.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
}
}
So my question is how can i modify my code so that i can save a file currently open without having the SaveFileDialog box opening everytime?
I do understand that it has something to do with the fact that i'm calling .ShowDialog but i don't know how to modify it.
When opening the file, save the FileName in a form-level variable or property.
Now while saving the file, you can use this FileName instead of getting it from a FileOpenDialog.
First declare a variable to hold filename at form level
// declare at form level
private string FileName = string.Empty;
When opening a file, save the FileName in this variable
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
// save the opened FileName in our variable
this.FileName = open.FileName;
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
And when doing SaveAs operation, update this variable
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
// save the new FileName in our variable
this.FileName = saving.FileName;
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
The save function can then be modified like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.FileName))
{
// call SaveAs
saveAsToolStripMenuItem_Click(sender, e);
} else {
// we already have the filename. we overwrite that file.
StreamWriter writer = new StreamWriter(this.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
In the New (and Close) function, you should clear this variable
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear the FileName
this.FileName = string.Empty;
richTextBox1.Clear();
}
Create a new string variable in your class for example
string filename = string.empty
and then
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(filename)) {
//Show Save filedialog
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
filename = save.FileName;
}
}
StreamWriter writer = new StreamWriter(filename);
writer.Write(richTextBox1.Text);
writer.Close();
}
The SaveFileDialog now only opens if fileName is null or empty
You will have to store the fact that you have already saved the file, e.g. by storing the file name in a member variable of the Form class you have. Then use an if to check whether you have already saved your file or not, and then either display the SaveFileDialog using ShowDialog() (in case you haven't) or don't and continue to save to the already defined file name (stored in your member variable).
Give it a try, do the following:
Define a string member variable, call it _fileName (private string _fileName; in your class)
In your saveToolStripMenuItem_Click method, check if it's null (if (null == _fileName))
If it is null, continue as before (show dialog), and after getting the file name, store it in your member variable
Refactor your file writing code so that you either get the file name from the file dialog (like before), or from your member variable _fileName
Have fun, C# is a great language to program in.
First, extract method from saveAsToolStripMenuItem_Click: what if you want add up a popup menu, speed button? Then just implement
public partial class Form1: Form {
// File name to save text to
private String m_FileName = "";
private Boolean SaveText(Boolean showDialog) {
// If file name is not assigned or dialog explictly required
if (String.IsNullOrEmpty(m_FileName) || showDialog) {
// Wrap IDisposable into using
using (SaveFileDialog dlg = new SaveFileDialog()) {
dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
dlg.Title = "Save File";
dlg.FileName = m_FileName;
if (dlg.ShowDialog() != DialogResult.OK)
return false;
m_FileName = dlg.FileName;
}
}
File.WriteAllText(m_FileName, richTextBox1.Text);
this.Text = Path.GetFileNameWithoutExtension(m_FileName);
return true;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
// SaveAs: always show the dialog
SaveText(true);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
// Save: show the dialog when required only
SaveText(false);
}
...
}

SaveFileDialog does not save the filename or path

I want to use a SaveFileDialog and when clicking on the Save Button I want to save the filename and the path into seperate variables. Here is the code:
private void Button_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = "SaveFile";
saveFileDialog1.DefaultExt = ".txt";
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt";
saveFileDialog1.Title = "Save a Text File";
saveFileDialog1.FileOk += saveFileDialog1_FileOk;
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string filename = System.IO.Path.GetFileName(saveFileDialog1.FileName);
string name = saveFileDialog1.FileName;
var test = System.IO.Path.GetDirectoryName(saveFileDialog1.FileName);
}
The dialog opens and it triggers the saveFileDialog1_FileOk Event but I get an empty string for the filename and the solution for getting the path (without filename) does not work. What am I doing wrong?
The main problem you have is using 2 instance of SaveFileDialog.
You show one dialog and then try to read File from another dialog that is obviously empty.
Pay attention that in your button click you are creating a new local instance and show it, and then in FileOk you are using another instance that seems to be a form level member.
Fix 1:
You can simply remove SaveFileDialog saveFileDialog1 = new SaveFileDialog(); because it seems you have saveFileDialog1 as a member of your form.
Fix 2:
You can use SaveFileDialog this way:
var sfd= new SaveFileDialog();
//Other initializations ...
//sfd.Filter= "Text files (*.txt)|*.txt|All files (*.*)|*.*";
//sfd.DefaultExt = "txt";
if(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MessageBox.Show(sfd.FileName);
//ِDo something for save
}
else
{
//Do something for cancel if you want
}
Then you can access to selected file using FileName property, for example MessageBox.Show(sfd.FileName);
Check this example from MSDN (https://msdn.microsoft.com/de-de/library/system.windows.forms.savefiledialog(v=vs.110).aspx):
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
You only have to check the return value of saveFileDialog1.ShowDialog() to know whether the user has clicked ok or not.
Then, you can use the FileName property which contains the selected file path.
EDIT: To get the folder path of the file, you can use this:
string folderPath = new DirectoryInfo(saveFileDialog1.FileName).Name;

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

OpenFileDialog Control - How Can I Grab the Selected Path and Show it in a Text Box?

Here is my snippet:
private void btnBrowseCInv_Click(object sender, EventArgs e)
{
ofdBrowseVInv.Title = "Locate Customer Invoice File";
ofdBrowseVInv.Filter = "Portable Document Format (*.pdf)|*.pdf|All Files (*.*)|*.*";
ofdBrowseVInv.FileName = "";
ofdBrowseVInv.FilterIndex = 0;
ofdBrowseVInv.InitialDirectory = "";
ofdBrowseVInv.CheckFileExists = true;
ofdBrowseVInv.CheckPathExists = true;
if (ofdBrowseVInv.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//txtInvoicePathCInv.Text = ofdBrowseVInv... What property should i use?
}
}
As you see below, once a user pick a file and click open. I want the selected path to show on the pointed text box which is named "txtInvoicePathCInv". Any idea?
I'm using Windows Application...
alt text http://img708.imageshack.us/img708/54/99763211.jpg
Use the FileName property:
txtInvoicePathCInv.Text = ofdBrowseVInv.FileName;
This will give you the whole path, but you can always just use the directory part of it, using Path.GetDirectoryName:
txtInvoicePathCInv.Text = Path.GetDirectoryName(ofdBrowseVInv.FileName);
string filename = System.IO.Path.GetFileName(ofdBrowseVInv.FileName);
string path = System.IO.Path.GetDirectoryName(ofdBrowseVInv.FileName);

Categories

Resources