Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

StreamWriter?

hello world streamwriter stream

  • Please log in to reply
7 replies to this topic

#1 Colo

Colo

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 23 June 2010 - 09:17 AM

Hello.
I was wondering if someone could tell me why my script isn't working?

I expect it to write "Hello word" to log.txt on my desktop?

public struct _cnf
    {
        public string logS;
    }

     static void form1(_cnf cnf)
     {
         cnf.logS = "C:\\Users\\Tom\\Desktop\\log.txt";
         StreamWriter logF = new StreamWriter(cnf.logS);
         logF.WriteLine("Hello World");
     }

There are no compiling errors, it just doesn't write anything in log.txt

any ideas? :(

thanks.
  • 0

#2 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 23 June 2010 - 09:58 PM

Try this:
using( StreamWriter logF = new StreamWriter(cnf.logS) )
{
    logF.WriteLine("Hello World");
}

Edited by dargueta, 23 June 2010 - 10:00 PM.
Fixed retarded and unhelpful question

  • 0

sudo rm -rf / && echo $'Sanitize your inputs!'


#3 Davide

Davide

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 484 posts

Posted 23 June 2010 - 11:38 PM

You forgot to close your text file, therefor it's changes have not been saved.
         cnf.logS = "C:\\Users\\Tom\\Desktop\\log.txt";
         StreamWriter logF = new StreamWriter(cnf.logS);
         logF.WriteLine("Hello World");
         logF.Close();
You can do either this or how dargueta showed you.

Last edited by dargueta; Today at 09:00 AM.
Reason: Fixed retarded and unhelpful question

Nice one.
  • 0
Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics

#4 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 24 June 2010 - 07:37 AM

That's kinda odd, because the operating system should close all file handles and flush anything in the buffers automatically. Then again, it is Windows... :D
  • 0

sudo rm -rf / && echo $'Sanitize your inputs!'


#5 Davide

Davide

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 484 posts

Posted 24 June 2010 - 10:53 AM

That's kinda odd, because the operating system should close all file handles and flush anything in the buffers automatically. Then again, it is Windows... :D

What :| ?!?!!?!?!?! Dude, that's availble for any OS you code on, I learned that in 9th grade. You don't get it, if it's not closed, things are not saved. This is what the using stement does after all, it closes the stream since it's a disposable object.
  • 0
Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics

#6 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 24 June 2010 - 10:21 PM

Dude...I don't say things without a reason. Before you go dismissing what other people say, check to make sure they don't know something that you don't.

WikiBooks.org:

Windows will automatically close the handle when the program closes. However, it is a more expensive operation for Windows to do it for you, and can waste time on your system. It is a good idea to always explicitly close all your handles before you exit your program.


Also look here.
In the operating system class I took a few months ago, we had to implement system API like this; one of the things we had to do was close all open descriptors in the terminating program. Check here for the project requirements (close() specs are slightly more than half the way down).

Even if the operating system didn't close them for you, take a look at the source code for the ofstream object in C++:
/**
       *  @brief  Possibly flushes the stream.
       *
       *  If @c ios_base::unitbuf is set in @c os.flags(), and
       *  @c std::uncaught_exception() is true, the sentry destructor calls
       *  @c flush() on the output stream.
      */
      ~sentry()
      {
    // XXX MT
    if (bool(_M_os.flags() & ios_base::unitbuf) && !uncaught_exception())
      {
        // Can't call flush directly or else will get into recursive lock.
        if (_M_os.rdbuf() && _M_os.rdbuf()->pubsync() == -1)
          _M_os.setstate(ios_base::badbit);
      }
      }
Notice that the destructor here automatically flushes the file when the stream object is being destroyed, provided that there aren't any pending uncaught exceptions and such. If Microsoft were consistent--and in this case it would behoove them to do so--they should do the same with the stream objects in C#.

With everything I've run into so far, you don't have to close the file descriptors, but you should. If you leave too many open it'll waste your memory and use up resources, but they'll all get flushed before you exit. (If your program crashes, though, that's not entirely guaranteed. Depends on the system and how your program crashes.) Yes, I now realize that C# is different (looked at the specs) but like I said, I had a well-based reason for my last post.

Edited by dargueta, 24 June 2010 - 10:23 PM.
Formatting

  • 0

sudo rm -rf / && echo $'Sanitize your inputs!'


#7 zoranh

zoranh

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 187 posts

Posted 08 July 2010 - 02:07 PM

Guys,

Your argument has gone astray. The point is not in closing the handle - yes, operating system will always close all handles of the process when process is being shut down. However, OS didn't get the data written to the stream writer because those data are still in the writer's buffer. It has nothing to do with the OS.

So let's do some examples that demonstrate this.

First example:
You don't necessarily have to dispose the stream writer in order to have data written to disc. You just have to flush it:
StreamWriter logF = new StreamWriter(@"D:\tmp.txt");
string part = "01234567\r\n";

logF.Write(part);
logF.Flush();

This code alone will have data written to disc even before you close the process (e.g. enter the breakpoint after flush and open the file - you'll see its content there). However, it is bad practice not to dispose stream writer, because otherwise file on disc remains locked for writing quite indefinitely (until the writer is finalized by the GC).

Second example
You can set the stream writer's AutoFlush property to true. Then the writer will call flush on every call to Write method. This is quite bad behavior having on mind disc performance:
StreamWriter logF = new StreamWriter(@"D:\tmp.txt");
string part = "01234567\r\n";

logF.AutoFlush = true;

for (int i = 0; i < 1000; i++)
    logF.Write(part);

This code will produce a file which is exactly 10,000 bytes in size.

Third example
If you omit AutoFlush=true line and do not flush manually and do not dispose the writer, then writer will flush data every time its internal buffer is full. In my test it occurs on every 1 kB, i.e. every 1024 bytes, and even then data will be visible in file only after the process is shut down regularly. That's the handle closing part you've been talking about - OS and disc themselves also have buffers and do not flush data to the medium more often then appreciated. But when OS closes the handle, it forces flush of all accompanying buffers.

StreamWriter logF = new StreamWriter(@"D:\tmp.txt");
string part = "01234567\r\n";

for (int i = 0; i < 250; i++)
    logF.Write(part);

This piece of code in my test produces a file of 2048 bytes in length, and not 2500 as it has tried to do.

Fourth example
Another solution is to set up your own buffer size:
StreamWriter logF = new StreamWriter(@"D:\tmp.txt", false, Encoding.Default, 719);
string part = "01234567\r\n";

for (int i = 0; i < 250; i++)
    logF.Write(part);

This code establishes stream writer with exactly 719 bytes of buffer space. Once the code is executed and process shut down regularly, the file will remain with 2157 bytes of data (instead of attempted 2500 bytes), which means that stream writer has flushed three times on its own.

Hope this has clarified the issue.

Edited by zoranh, 09 July 2010 - 06:20 AM.
Corrected typo in number

  • 1

#8 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 08 July 2010 - 09:42 PM

Well thought-out and to the point, zoranh. +rep.
  • 0

sudo rm -rf / && echo $'Sanitize your inputs!'






Also tagged with one or more of these keywords: hello world, streamwriter, stream

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download