-2

So not sure why this does not work. I have this in a button on my web form.

protected void btnSave_Click(object sender, EventArgs e)
{
    using (StreamWriter sw = new StreamWriter("C:\\temp\\test.txt"))
    {
        sw.Flush();
        sw.WriteLine(txtDescription.Text);
    }
}

When I type something into that text box and click the save button, nothing happens. No matter if the file exists ahead of time or not.

Not really sure what I missed. I have tried closing the streamwriter after the write line but that doesn't seem to work either. I am wondering if there is something in my form that needs to be changed.

maltman
  • 454
  • 1
  • 7
  • 28
  • 1
    try to swap lines of code: `sw.Flush();` has to be called in the end. – Maxim Kreschishin Oct 17 '17 at 18:34
  • 1
    Well, flushing the writer _before_ you've written anything is pointless. But shouldn't hurt anything. The code you posted is "fine" as far as it goes. So whatever your problem, it's related to something other than the code you posted. Without more context, there's no way to know if you have simply failed to subscribe to the button's `Click` event, or you have some kind of file permissions issue, or what. You should just set a break point and debug the code to see what it actually does. If you want help here, you need to provide a good [mcve] that reliably reproduces the problem. – Peter Duniho Oct 17 '17 at 18:35
  • 1
    @Maxim: flushing first isn't useful, but neither would moving the flush to after the write. Closing the writer (which `using` does when execution leaves that block of code) will also flush the writer. – Peter Duniho Oct 17 '17 at 18:36
  • @Peter Duniho. As soon as you said it I knew I did it. Had 3 buttons. Forgot the onclick event on that one. Thanks for all of the responses everyone. – maltman Oct 17 '17 at 19:39

2 Answers2

1

If there is no exception this code will work. This means that you are making a mistake not shown here. Maybe you are looking at the wrong drive. Or, you are not noticing exceptions (swallowing them somehow). Maybe txtDescription.Text does not contain what you expect?! Single-step through this code with the debugger and check for that file immediately after sw has been disposed.

Although I cannot tell you the specific mistake I can tell you to look elsewhere and to make sure that you are correctly interpreting what you see.

It's simpler to call File.WriteAllText but that will not fix the mistake.

usr
  • 168,620
  • 35
  • 240
  • 369
-2

Try this:

StreamWriter OUTPUT;
string myfile = "C:\\temp\\test.txt";
OUTPUT = File.CreateText(myfile);
OUTPUT.WriteLine(txtDescription.Text);
OUTPUT.Close();

It is very similar to your code except using "File.CreateText" method. Hope it helps

FSmith94
  • 13
  • 1