save the content of the text box to a variable c# - 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

Related

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

issue with 'file browser dialog' when combining files

Currently, I have a browser dialog that opens and allows the user to select a folder in which doc / docx files will be merged into one file. At the moment, it is rigged up to merge files once the 'DialogResult.ok' button is dismissed in the browser dialog. as shown below:
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
}
private void combineButton_Click(object sender, EventArgs e)
{
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + AllDocFolder.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
the issue i am having is that i want the 'combineButton' to merge the documents as opposed to the 'DialogResult.ok'. When i copy the lines:
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
into the combineButton area, i get an error saying 'the name 'selectedFolder' does not exist in the current context'. This may be a stupid question, but is there a quick way to remedy this?
As far as I understand your problem, you want to split the folder selection and the merging of the documents, right?
So you could put the information about the target directory into a class variable:
public class MyForm
{
private string[] _sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
_sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (_sourceFiles != null && _sourceFiles.Length > 0)
{
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(_sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + _sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

WinCE 5.0 How Can I Get Directory

Hi all firstly sorry for my English but i hope you can understand me..
Im doing a project on VS2008-Smart Device Project-WinCE 5.0 Project.
I need to create text file to DATA folder which is under the main directory of program.
There is my code, there is no error messege but its not creating text file.My directory always returns null.
Whats wrong with that code?
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
try
{
StreamReader Read_File= File.OpenText(path);//Dosyayı açmaya çalış olmaz ise catch bloğuna geç
ReadFile.Close();
}
catch
{
StreamWriter Write_File= File.CreateText(path+ i.ToString()+".txt");// yeni dosya oluştur.
Write_File.Close();
}`
And heres the form2 which includes listbox and listbox shows directory for if there is a file or not..
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
path = path + "\\DATA";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] rgFiles = di.GetFiles();
foreach (FileInfo fi in rgFiles)
{
listBox1.Items.Add(fi.Name);
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
chosen_file = listBox1.GetItemText(listBox1.SelectedItem);
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
else
{
MessageBox.Show("HATA:Hiçbir Değer Seçilmedi!"); // That means error:no value chosen!
}
}
Your code does not prepare the path variable properly. In one case it contains a file name, in another case it contains only a path name:
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
Then you try to open a file - even though the variable does not contain a file name in the first place. If that leads to an exception, you try to create a file, but actually, you're not adding a path separator to the path. So I think your catch block should read:
StreamWriter Write_File= File.CreateText(path + "\\" + i.ToString() + ".txt");// yeni dosya oluştur.
Write_File.Close();

How to give userchoice file name in browserdialog box

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.

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))

Categories