Create and write into the txt file with one button - c#

I would like to create the txt file that has name from my textbox1 and at the same time, I would like to write in it text from my textbox2.
Can you help me?
I have tried this
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text +
".txt";
File.Create(path);
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(textBox1.Text);
}
}

I would suggest you first check if the file already exists, and only create it if not.
Something like:
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text + ".txt";
if (!File.Exists(path))
{
File.Create(path);
}
using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}
}
Note : in case you would like your code to append line to the file and not to re-write it, change the secont argument to "true": new StreamWriter(path, true)
Note 2 : You wrote the value of the first text box to the file instead of the second one. hence, in your code the text in the file will be the same as it's name.

using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}

Related

How do I take a users input for their login email and find a file that matches it?

Here is my code, I've tried using Streamreader but it won't work when I put in the file path.
private void LoginFormbtn_Click(object sender, EventArgs e)
{
StreamReader reader = new StreamReader("/Participants/");
using (reader)
if(File.Exists("txtEmailID.Text" + ".txt"))
{
Userform Userf = new Userform();
Userf.Show();
MessageBox.Show("Success!");
}
}
Try changing this:
if(File.Exists("txtEmailID.Text" + ".txt"))
into this:
if(File.Exists(txtEmailID.Text + ".txt"))
Also i would have declare the StreamReader like this:
using (StreamReader reader = new StreamReader("/Participants/"))
{
// your code
}

in c# Read full txt file

I tried to do a form application and I have a problem about use StreamReader feature. in StreamWriter feature, I did it but StreamReader just read the last line and The txt file contains, in many rows for example: names and phone numbers but like I said the code read last line
private void button2_Click(object sender, EventArgs e)
{
//1
StreamWriter sw;
sw = File.AppendText("metinbelgesi.txt");
sw.Write(textBox1.Text + " ");
sw.Write(textBox2.Text + " ");
sw.WriteLine(textBox3.Text+"." );
sw.Flush();
sw.Close();
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
FileStream fs = new FileStream("metinbelgesi.txt", FileMode.Open, FileAccess.Read);
StreamReader sw = new StreamReader(fs);
//sw = File.AppendText("metinbelgesi.txt");
string yazi = sw.ReadLine();
while (yazi != null)
{
richTextBox1.Text = yazi;
}
sw.Close();
fs.Close();
}
else
{
MessageBox.Show("First, You Join.");
}
}
What do I do?
You are reading it line by line and keep overwriting richTextBox1 with the next line... try:
richTextBox1.Text = "";
while (yazi != null)
{
richTextBox1.Text += yazi;
yazi = sw.ReadLine();
}
Or, if you don't need to parse each line, you can read it all in one go:
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}
According to your code, you're only reading the first line. There should be a ReadLine() statement inside your loop as well.
Pay attention that you will always overwrite the contents of the textbox with the line of text you've just read.
So, when you've finished your loop, only the last line that you've read will occur in the textbox.
For simplicity, you can also have a look at the File class and more specifically the ReadAllLines() method.
You should probaby try to make your life easier by using some of the simpler File operations.
Try this instead:
private void button2_Click(object sender, EventArgs e)
{
File.AppendAllText("metinbelgesi.txt", $"{textBox1.Text} {textBox2.Text} {textBox3.Text}.");
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}
else
{
MessageBox.Show("First, You Join.");
}
}

How to save text from the ListBox?

Can I use the "StreamWriter" function to save the text in the ListBox?
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = "Text files|*.txt";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
sw.WriteLine(listBox1.Text);
sw.Close();
}
Property ListBox.Text only works with the selected item. You, I suspect, need all the elements. If the ListBox rows are stored, it is possible to do so:
File.WriteAllLines(saveFile1.FileName, listBox1.Items.OfType<string>());
You should use string SelectedItem of the ListBox
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
sw.WriteLine(listBox1.GetItemText(listBox1.SelectedItem));
sw.Close();
}
If you want to save all items on your Listbox using StreamWriter, loop through all items and pass it on a string, or stringbuilder then write it on your file:
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
string text = "";
foreach (var item in listBox1.Items)
{
text += item.ToString() + Environment.NewLine; //I added new line per list.
}
sw.WriteLine(text);
sw.Close();
}
If you want the selected text instead, you can just use the SelectedItem:
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
sw.WriteLine(listBox1.SelectedItem);
sw.Close();
}

Write textbox text to a file while keeping newlines

I have tried using:
StreamWriter.WriteLine()
StreamWriter.Write()
File.WriteAllText()
But all of those methods write the textbox text to the file without keeping newlines and such chars. How can I go about doing this?
EDIT:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(s.FileName, richTextBox1.Text);
}
}
I am using a multiline RichTextBox to do this.
To expand on tzortzik's answer, if you use StreamWriter and simply access the RichTextBox's Lines property, it will do the work for you:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(s.FileName))
{
foreach (string line in richTextBox1.Lines)
{
sw.WriteLine(line);
}
}
}
}
Maybe this would help. Is from StreamWriter class documentation.
string[] str = String.Split(...);
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
The idea is to get the text from your textbox and then split it after \n char. The result will be an array of strings, each element containing one line.
Later edit:
The problem is that return carriage is missing. If you look with debugger at the code, you will see that your string has only \n at a new line instead of \r\n. If you put this line of code in you function, you will get the results you want:
string tbval = richTextBox1.Text;
tbval = tbval.Replace("\n", "\r\n");
There should be other solutions for this issue, looking better than this but this one has quick results.

How to save text font (which was set up manually) with a text in C#

I set up the font manually for the labels, however, when I am saving it as a Word Document the font which I set up previously disappears. I do not know how to figure it out
private void button1_Click(object sender, EventArgs e)
{
string text = label1.Text + textBox1.Text + "\r\n\r\n\r\n" +
label2.Text + textBox2.Text + "\r\n\r\n\r\n";
sSaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Microsoft Word| *.doc";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
MessageBox.Show(path);
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(text);
}
}
}
}
StreamWriter (basically) writes a string (of characters) to a file. Word formatting is not that simple. If you want the formatting then it gets more complicated.
See this MSDN article for more info on formatting Word documents. You need an object that can control the document.

Categories