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();
}
}
CodePudding user response:
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.
CodePudding user response:
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();
}
}