0

I am still newbie to C# and I'm making a test program that writes the DateTime.Now every second. I tried using this and it worked:

StreamWriter sw = new StreamWriter("D:\Hello.txt", true);
sw.WriteLine(DateTime.Now);
sw.Close();

However, when I tried including a FileStream, it didn't work. What seems to be the problem? Here's my code:

FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now);
sw.Close();
fs.Close();

Note: I am using a timer, it executes the code every second..

Update: I tried placing the code(the one that has the filestream) inside a button (w/out timer). Whenever I clicked the button, it just replaces the line in the textfile.. This is a code that appends a text to the textfile: StreamWriter sw = new StreamWriter("D:\Hello.txt", true);

How will I do it in a filestream? I cannot use FileMode.Append in FileStream because it required=s the FileAccess to be write-only.

8
  • 1
    "it didn't work" is far too vague for us to help you. Please give more details. Oh, and you should use using statements to close resources in a more robust way.
    – Jon Skeet
    Aug 23, 2012 at 6:09
  • please provide Exception details and make sure that file is not open or in use by another process. I dont think this has anything to do with the timer.
    – pskk
    Aug 23, 2012 at 6:11
  • Don't you think using Filemode.Append is better...just a suggestion.
    – Abhineet
    Aug 23, 2012 at 6:16
  • @pssk - I think it should show an error if it is being used by another process, but I'll check it again.. Aug 23, 2012 at 6:17
  • @Ravi - I tried setting breakpoints, it passes through the code that writes the text but still doesn't write in the textfile.. Aug 23, 2012 at 6:19

7 Answers 7

1

Since you are executing the code every second then its not a good idea to create FileStream and StreamWriter object everytime, because sometimes the file will remain under lock condition and the filestream will miss to acquire the handle.

As you are writing to single file its good to initialize a FileStream and subsequent StreamWriter in the constructor while leaving the refrence to them in class scope;then calling it every second on a thread for sw.WriteLine(DateTime.Now); should help.

And further never miss try catch in a filestream. They help a lot to locate the discrepancies.

1
  • Are you sure, it really closes within a second????Take the snap of exception logged, you'll learn more.
    – perilbrain
    Aug 23, 2012 at 7:17
0

May be try to use File?

File.AppendAllText(@"D:\Hello.txt", DateTime.Now.ToString());

or

File.WriteAllText(@"D:\Hello.txt", DateTime.Now.ToString());

to overwrite

1
  • I have to use FileStream because it has the filemode, fileacces and fileshare which I needed. Aug 23, 2012 at 6:34
0

You should use something like this because it works fine for me. If it does not work for you, you have to add more details

        using (var fs = new FileStream("path", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            fs.Seek(0, SeekOrigin.End);
            using (StreamWriter sw = new StreamWriter(fs) { AutoFlush = true })
            {
                sw.WriteLine("my text");
            }
        }

But remember I would not create it every second. Why don t you store a Streamwriter object as field when you call Timer.Start? So you would not have to create it every second. (rememer to dispose it when you stop the timer)

0

Should work:

FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now);
sw.Flush();
sw.Close();
fs.Close();
0

I already solved it.. :) I just have to use FileMode.Append, FileAccess.Write as an argument in the filestream. Reason for not doing FileMode.Append earlier is because it needs FileAccess to be Write only. I thought switching the FileAcess to Write only will prevent the user from reading the file. So stupid of me.. This is my code:

private void timer1_Tick(object sender, EventArgs e)
    {

        FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
        StreamWriter sw = new StreamWriter(fs);
        sw.WriteLine(DateTime.Now);
        lbTimer.Items.Add(DateTime.Now);
        sw.Close();
        fs.Close();

    }

Last question, what is setting the FileAccess to Write only for when you can still read it?

0

Try calling StreamWriter.Flush() before StreamWriter.Close().

-1

You might wanna look here

How to: Write to a Text File (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

1
  • Don't you think this is not an answer, just a comment?
    – L.B
    Aug 23, 2012 at 6:10

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.