lovely c# OpenOrCreate

Have you ever needed to save something to a file in c#?

You have you say.

Well heres a nifty trick I just found. Its old and simple, but its new to me so I’m going to share it anyway.

If you were doing this -

...
System.IO.FileStream fs=new System.IO.FileStream("test.pdf",System.IO.FileMode.CreateNew);
...

and the file already existed it would throw an exception. My initial reaction would be to wrap it in something that checked whether the file was already existent and then change what happens as appropriate.

But no! There is another way.

Thanks to some thoughtful developers you can do this instead…

...
System.IO.FileStream fs=new System.IO.FileStream("test.pdf",System.IO.FileMode.OpenOrCreate);
...

Now isn’t that just lovely. What a clever little function, System.IO.FileMode.OpenOrCreate - Thanks Microsoft!

phils super shot

Andrey said,

January 10, 2007 @ 10:27 am

I just fixed critical bug in my program, and googling for other loosers, who use FileStream(OpenOrCreate).

catch is - you are not truncating file if it already exisis.

RSS feed for comments on this post · TrackBack URI

Leave a Comment