Writing to a Text File
-
I am new to codeproject, and relatively new to C#. Eventually i got bored of... non-saving uses... and decided i needed to save something. So i tried.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;namespace FileMaker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}private void btnCreate\_Click(object sender, EventArgs e) { Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "txt files (\*.txt)|\*.txt|All files (\*.\*)|\*.\*"; saveFileDialog1.FilterIndex = 1; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = saveFileDialog1.OpenFile()) != null) { StreamWriter wText = new StreamWriter(myStream); wText.Write("CHEESE"); myStream.Close(); } } } }
}
It doesn't work. When i run the program and click on the button, and go through the save file dialog, a file does appear, but "CHEESE" does not appear in the text file. I cannot figure out why this doesn't work. So how do i fix this so that "CHEESE" appears in the file? Thanks to anybody who helps!
-
I am new to codeproject, and relatively new to C#. Eventually i got bored of... non-saving uses... and decided i needed to save something. So i tried.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;namespace FileMaker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}private void btnCreate\_Click(object sender, EventArgs e) { Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "txt files (\*.txt)|\*.txt|All files (\*.\*)|\*.\*"; saveFileDialog1.FilterIndex = 1; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = saveFileDialog1.OpenFile()) != null) { StreamWriter wText = new StreamWriter(myStream); wText.Write("CHEESE"); myStream.Close(); } } } }
}
It doesn't work. When i run the program and click on the button, and go through the save file dialog, a file does appear, but "CHEESE" does not appear in the text file. I cannot figure out why this doesn't work. So how do i fix this so that "CHEESE" appears in the file? Thanks to anybody who helps!
try closing the streamwriter before closing the stream... :)
Luc Pattyn
-
try closing the streamwriter before closing the stream... :)
Luc Pattyn
wText.Close(); MyStream.Close(); unless u close the writer, buffered things will not be explicitly fwded to the disk.