How to give userchoice file name in browserdialog box - c#

Hi in my windows form application i want to save some data in a folder and when user selcts the browse button it should browse to reqired folder and should consist of a textbox to enter the filename of user choice. How can i achieve this . The below code is not working for me
private void OutputFolder_button_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
try
{
if (fd.ShowDialog() == DialogResult.OK)
{
if (string.IsNullOrEmpty(OutputFolder.Text))
{
MessageBox.Show(" Please provide output file to do backup ");
return;
}
outputFileName = fd.SelectedPath + "\\" + outputFileName;
File.Create(outputFileName).Dispose();
OutputFolder.Text = outputFileName;
//File.Create(outputFileName);
DisplayMainWindow("Selected path to backup" + outputFileName);
Logger.Log("Selected path to backup" + outputFileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception" + ex);
}

Sounds like you need the SaveFileDialog class.

You need a SaveFileDialog.
The example in the MSDN page should be enough to get you started.

Related

save the content of the text box to a variable c#

I have the following method in windows form
private void btnSelectNuevo_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
try
{
string fichero = openFileDialog2.FileName.ToString();
txtbox_sel_fich.Text = fichero;
if (string.IsNullOrEmpty(txtbox_sel_fich.Text) == true)
{
MessageBox.Show("file not selected", "return file selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
}
and another method:
private void btnsubir_Click(object sender, EventArgs e)
{
string reply = "";
string fichero = "";
fichero = textbox_select.Text.ToString();
// string ruta = textbox_select.Text.ToString();
// FileInfo fich = new FileInfo(ruta);
// fichero = fich.Name;
if (fichero == readLastFile(fichero))
{
createLog(fichero + ":this file" + fichero + " You have already been imported previously. No action is realized\n");
MessageBox.Show("This file" + "'" + fichero + "'" + " You have already been imported");
}
else
{..
how can you see I have a method called "readLastFile (fichero)"; what it does is check in MySql in the "File" table if there is a file already imported with that name that I pass as a parameter, if it exists it does not import it to the DDBB and the program ends but if it does not exist it does the import.
The problem I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx) since when I am going to do the check tells me it doesn't exist and starts loading when it shouldn't.
Some help?
I don't know if I am saving it correctly. THANKS FOR YOUR SUPPORT
I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx)
Use Path.GetFileName(...)
Path is part of the System.IO namespace

I have a problem in saving file with the FolderBrowserDialog

I have this code:
private void button1_Click(object sender, EventArgs e)
{
string x = "Name: " + label1.Text + " " + "FamilyName: " + label2.Text + " " + "FatherName: " + label3.Text + " " + "PhoneNumber: " + label4.Text;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
if (radioButton1.Checked == true)
{
System.IO.File.WriteAllText(folderBrowserDialog1.SelectedPath + label1.Text + ".txt", x);
MessageBox.Show("The file registered.");
}
else if (radioButton2.Checked == true)
{
System.IO.File.WriteAllText(folderBrowserDialog1.SelectedPath + label1.Text + ".doc", x);
MessageBox.Show("The file registered.");
}
else
{
MessageBox.Show("Please choose one of the formats.");
}
}
}
And this is for store some information from labels in a file, and dynamically selects the file name from label1. Then I put a radio button to choose between saving the file in txt format or doc format. After selecting one of the formats and clicking on the Save button, the folderBrowserDialog opens so I can choose the path I want to save my file there. But when I chose my path, let's say that I chose this path: 'G:\SavingFile\TextFiles', instead of saving the file in the TextFiles folder, saves it in the SavingFile folder.
My question is why it doesn't save the file in the last folder? And how can I fix it?
You should not concatenate your paths as string but use System.IO.Path.Combine instead. as this will also take care of the correct path-separators, which are missing from your code as SelectedPath does not end with a path-separator
So in your case
var filepath = System.IO.Path.Combine(folderBrowserDialog1.SelectedPath, label1.Text + ".txt");
System.IO.File.WriteAllText(filepath, ....);
This will take care of the required path separators.
If you are using .Net Core you might also use System.IO.Path.Join. But be aware there are some differences in the behaviour of these two methods with regards to rooting the resulting path. See the linked docs for details.
I also found another way to save my files that is easier than the way that I did above. I can simply use saveFileDialog.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllText(saveFileDialog1.FileName, x);
}

C# WinForms - Error on OpenFileDialog MultiSelect: "Index was outside the bounds of the array."

In debug mode, while running the C# WinFOrms App, After I select the files through the OpenFileDialog, I get the
Error: Could not read file from disk.
Original error: Index was outside the bounds of the array.
Do you have any idea on how to fix this Error?
Here's my code:
// When the user clicks on Select Files Button, this happens
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|" + "All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (this.sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string tempFolder = System.IO.Path.GetTempPath();
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
i++;
System.IO.File.Copy(FileName, tempFolder + #"\" + FileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
//method for the sourcefileOpenFileDialog. Do I need anything here?
private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
{
}
//method for the listbox. Do I need anything here?
private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
Thanks!
What you are doing doesn't seem to make a lot of sense. What is the following line supposed to do?
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
Just change your foreach to this:
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + FileName);
System.IO.File.Copy(FileName, Path.Combine(tempFolder, Path.GetFileName(FileName)));
}
The error arises from the fact, that you have two variables named sourceFileOpenFileDialog. One is a member of your class and one is declared inside the method.
The one that is declared inside the method is only ever used in the following line:
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
Because this instance is not used to show the dialog to the user, its FileNames property has a Length of 0 and therefore trying to access any items in it results in the exception.
Update:
There is one more problem:
FileName is a complete path, so appending it to the temp path will result in an invalid path. Also, consider using Path.Combine to combine two paths:
Path.Combine(tempFolder, Path.GetFileName(FileName))

C# WinForms - Multiselect not working on OpenFileDialog & Listbox

Hey Everyone,
Sorry to bother you with this, but I'm having an issue with selecting multiple xlsx files through a file browser window in a winforms application when debugging and can't figure out what I did wrong.
Problem: I set Multiselect=true under the OpenFileDialog but I still cannot select more than one file.
What do I need to change to get the multiSelect feature to work?
Do I need to add anything under sourceFileOpenFileDialog method?
Do I need to add anything under listBoxSourceFiles_SelectedIndexChanged method to get the filenames to load correclty in the listbox?
// When the user clicks on Select Files Button, this happens
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|" + "All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
{
using (myStream)
{
foreach (string FileName in sourceFileOpenFileDialog.FileNames)
{
sourceFileOpenFileDialog.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
i++;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
//method for the listbox. Do I need anything here?
private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
//method for the sourceFileOpenFileDialog. Do I need anything here?
private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
{
}
I updated the code to reflect sourceFileOpenFileDialog and the MultiSelect or Title doesn't work... Perhaps I'm referencing the onfiledialog wrong? is this the proper prefix to use?
Thanks for looking!
You are using two OpenFileDialogs. You display sourceFilesList but you initialized sourceFileOpenFileDialog. Using consistent naming rules religiously is a great way to avoid bugs like these btw.
Next problem, what is OpenFile() supposed to do when you selected more than one file? What is myStream actually used for?
You are setting up sourceFileOpenFileDialog but then use sourceFileList!!! Make up your mind and only use one.
Fixed the non-working MultiSelect by:
Updating the code to only use one variable sourceFileOpenFileDialog throughout the method and the MultiSelect or Title didnt work...
Removing all references to myStream. myStream was used in an example which i based my code off but i took it out and the multiSelect works!
Here's the working code:
// When the user clicks on Select Files Button, this happens
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|" + "All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string tempFolder = System.IO.Path.GetTempPath();
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
i++;
System.IO.File.Copy(FileName, tempFolder + #"\" + FileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
//method for the listbox. Do I need anything here?
private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
//method for the sourceFileOpenFileDialog. Do I need anything here?
private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
{
}

Opening multiple files (OpenFileDialog, C#)

I'm trying to open multiple files at once with the OpenFileDialog, using FileNames instead of FileName. But I cannot see any examples anywhere on how to accomplish this, not even on MSDN. As far as I can tell - there's no documentation on it either. Has anybody done this before?
You must set the OpenFileDialog.Multiselect Property value to true, and then access the OpenFileDialog.FileNames property.
Check this sample
private void Form1_Load(object sender, EventArgs e)
{
InitializeOpenFileDialog();
}
private void InitializeOpenFileDialog()
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
// ^ ^ ^ ^ ^ ^ ^
this.openFileDialog1.Title = "My Image Browser";
}
private void selectFilesButton_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
try
{
PictureBox pb = new PictureBox();
Image loadedImage = Image.FromFile(file);
pb.Height = loadedImage.Height;
pb.Width = loadedImage.Width;
pb.Image = loadedImage;
flowLayoutPanel1.Controls.Add(pb);
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n" +
"Details (send to Support):\n\n" + ex.StackTrace
);
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
+ ". You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
}
}
You can use this method for text files:
OpenFileDialog open = new OpenFileDialog();
open.Filter = "All Files *.txt | *.txt";
open.Multiselect = true;
open.Title = "Open Text Files";
if (open.ShowDialog() == DialogResult.OK)
{
foreach (String file in open.FileNames)
{
string temp = YourRichTextBox.Text;
YourRichTextBox.LoadFile(file, RichTextBoxStreamType.PlainText);
YourRichTextBox.Text += temp;
}
}

Categories