-2

I have a for loop (slowed down by a timer) and every second the loop save the date on a text file. but if i close the program before the process ends, the text file remains.

the thing is when i present in class, i will not have enough time to waste waiting for the program to end, and at the same time i need to suspend the thread at sometime so i can't just use a smaller loop and risk not having enough time to suspend and resume.

is there a way to save the file after every loop? so whenever i exit (form based application) i would have some data there?

5
  • If you desire a better answer than "Yes there is a way" then I would suggest that you post the code that you are having trouble with and maybe explain better what the problem is. Jan 12, 2013 at 21:28
  • please show some source code... what have you tried ?
    – Yahia
    Jan 12, 2013 at 21:28
  • is this winforms, wpf or ?
    – Mark Hall
    Jan 12, 2013 at 21:29
  • Why not show the code in question so that it won't lead to many assumptions?
    – MethodMan
    Jan 12, 2013 at 21:33
  • nevermind, lazyberezovsky got it Jan 12, 2013 at 21:36

3 Answers 3

1

Set StreamWriter.AutoFlush property to true. That will make writer flush its buffer to the underlying file stream after every call to StreamWriter.Write.

using(var writer = File.AppendText("fileName"))
{
    writer.AutoFlush = true;
    foreach(string line in lines)
        writer.WriteLine(line);
}
0
0

Maybe you can have another loop (also with a timer with less time) that always saves the data.

0

Try using this as saving to text file:

It will read old text and save old text and new text to it...

StreamReader sr = new StreamReader(path);
StreamWriter sw = new StreamWriter(path);
string old = sr.ReadToEnd();
sr.Close();
sw.WriteLine(old);
sw.WriteLine(date);
sw.Close();

Or you can make StreamWriter as public and on Form Closing event you can save it on closing... public StreamWriter sr = new StreamWriter("C:\\...")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.