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);
}
Related
I'm trying my first attempt at a "Save file" button.
It's going surprisingly well. :D
I have been able to get the file to combine multiple pieces of user-inputted text from different text-boxes into a single file and save it as a text file output.
Where I am stuck is that I'm trying to figure out how to split the text file into multiple lines for easier readability. I have tried searching for examples online, but everything I'm seeing shows the opposite, how to combine multiple text inputs into a single file. I've already got that.
Here's my code. I'm trying to break it into new lines where the long empty spaces are.
Thanks in advance.
private void button1_Click_2(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "Writing Prompt- " + Txt_Prompt_Title.Text;
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = sfd.FileName;
TextWriter sf = new StreamWriter (File.Create(path));
sf.Write("Writing Prompt: " + Txt_Prompt_Title.Text + " " + Lbl_Prompt_Output.Text + " " + Txt_Prompt_Notes.Text);
sf.Dispose();
}
}
This is simply a restatement of the OP's self-answer, incorporating the suggestions that were made in the comments. I'm also using the orginal using syntax, not everyone is using a recent compiler. If the OP updates his/her answer, I'll delete this:
private void button1_Click_2(object sender, EventArgs e)
{
using (var sfd = new SaveFileDialog()) {
sfd.Filter = "Text File|*.txt";
sfd.FileName = "Writing Prompt- " + Txt_Prompt_Title.Text;
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = sfd.FileName;
using (var sf = new StreamWriter (File.Create(path))){
sf.Write("Writing Prompt: " + Txt_Prompt_Title.Text +
"\n" +
"\n " + Lbl_Prompt_Output.Text +
"\n" +
"\n " + Txt_Prompt_Notes.Text);
}
}
}
}
What I didn't add was code that uses Environment.Newline instead of "\n", or code that gets rid of the string concatenation (which can cause a lot of garbage string objects that need to be garbage collected). One way to achieve both would be to use .WriteLine over and over again, as #MathieuGuindon suggests).
You probably want to look up string interpolation for creating strings that have the string rendering of other objects embedded in them.
You should really follow the link to the using statement that #jimi has pointed you to. It provides a way to make sure you properly Dispose of objects that implement IDisposable while making your code more readable.
I figured it out.
private void button1_Click_2(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "Writing Prompt- " + Txt_Prompt_Title.Text;
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = sfd.FileName;
TextWriter sf = new StreamWriter (File.Create(path));
sf.Write("Writing Prompt: " + Txt_Prompt_Title.Text +
"\n" +
"\n " + Lbl_Prompt_Output.Text +
"\n" +
"\n " + Txt_Prompt_Notes.Text);
sf.Dispose();
}
}
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
What would be the best way to save a windows form to a file with a few text boxes collecting user input. I using this at the moment:
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, tB1.Text);
File.WriteAllText(saveFileDialog1.FileName, tB2.Text);
}
This is fine for saving the input from the first text box but when it comes to the other it wont save the data entered.
If it was me I would use the StreamWriter / StreamReader Classes since they have WriteLine and Readline methods respectively.
i.e. something like this
private void button1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
{
sw.WriteLine(tB1.Text);
sw.WriteLine(tB2.Text);
sw.WriteLine(tB3.Text);
sw.WriteLine(tB4.Text);
sw.Close();
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
tB1.Text = sr.ReadLine();
tB2.Text = sr.ReadLine();
tB3.Text = sr.ReadLine();
tB4.Text = sr.ReadLine();
sr.Close();
}
}
}
Concatenate this two texbox then;
File.WriteAllText(saveFileDialog1.FileName, tB1.Text + Environment.NewLine + tB2.Text );
how about concatenating the two textboxes? for clarity,
string forSaving = tB1.Text + "\n" + tB2.Text;
File.WriteAllText(saveFileDialog1.FileName, forSaving);
or
File.WriteAllText(saveFileDialog1.FileName, tB1.Text + "\n" + tB2.Text);
UPDATE 1
string firstName = "FirstName: " + txtFirstName.Text;
string lastName = "LastName: " + txtLastName.Text;
string personAddress = "FirstName: " + txtAddress.Text;
string details = firstName + "\n" + lastName + "\n" + personAddress;
File.WriteAllText(saveFileDialog1.FileName, tB1.Text + "\n" + details);
The best way would probably be to create a method in your form that will return a string with all of the values from the TextBoxes into whatever format you want. Something like this would work:
File.WriteAllText(saveFileDialog1.fileName, OutputUserInfo());
Then inside OutputUserInfo() you can have whatever formatting to the data that you want so you can understand what they put in.
Edit Example of OutputUserInfo()
private string OutputUserInfo() {
return "First Name: " + tbFirstName.Text + Environment.NewLine +
"Surname: " + tbSurname.Text + Environment.NewLine +
"Address" + tbAddress.Text + Environment.NewLine;
// Just keep adding whatever you want on here.
// Add the descriptions if you want, it will probably help
}
You could also have this in different formats (CSV, or whatever). But if you're just doing a plain text file, this could be easiest. It is up to you though.
File.WriteAllText is probably bad because it overwrites your content.
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
Instead go with File.AppendAllText which
Appends the specified stringto the file, creating the file if it does not already exist.
There we go, use Encoding to Append all the string.
private void button1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string line = string.Format("{0},{1}"
, textBox1.Text
, textBox2.Text);
File.AppendAllText(saveFileDialog1.FileName, line, Encoding.GetEncoding(1252));
}
}
I'm trying to make sure that the user doesn't download a file that will replace an existing downloaded (same) file. Hence, I tried to create YesNo dialog for the user to confirm. However, even if there's no "sample.xml" in that folder, the YesNo dialog will still appear when the user click on Download button. May I know where did I do wrongly? I am lacking programming knowledge, sorry and please bear with me.
My code as below:
private void btnDownloadXML2_Click(object sender, EventArgs e)
{
if (#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" != null)
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to re-download the file? This will replace the old file!", "Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://www.lse.co.uk/chat/" + txtSharePriceSymbol.Text.ToString(),
#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml");
}
MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!");
}
else if (dialogResult == DialogResult.No)
{
MessageBox.Show("The file is not downloaded. Your old file remains.");
}
}
else if (#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" == null)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://www.lse.co.uk/chat/" + txtSharePriceSymbol.Text.ToString(),
#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml");
}
MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!");
}
}
You're checking the file path as a string to see if it's null.. it's never null, because it has the file path.
You'll need to use File.Exists(). Instead of this:
if (#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" != null)
Use this:
if (File.Exists(#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml"))
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.