473,480 Members | 1,711 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Filestreams

Hi,

I'm an IT guy who likes to think he can program. I have a generic question
about filestreams.

I'm putting together an application and need to write certain activities out
to a log file. I created a Log class to manage all file operations.

The class has Open, Close, and Record methods. I don't understand how the
FileStream object functions, though. If I create the object with FileMode =
OpenOrCreate and FileAccess = ReadWrite it seems I should be able to
attach/detach a StreamWriter object as necessary.

In fact, it works fine until I close the StreamWriter. When I reopen I find
the the FileStream is no longer writeable.

Is there a simple explanation to correct my misunderstanding of the
FileStream or a good tutorial on how they work that I should read. Forgive
me for not searching more on my own but I'm late for a meeting and I have to
get this code out the door asap.

Thanks, bob
Jan 10 '07 #1
7 1809
Hi,

Closing the StreamWriter closes the underlying Stream, in your case the
FileStream and so the file.
You could keep the StreamWriter open as long as you keep the FileStream
open.
Or you could not close the StreamWriter at all. I think, this is an
acceptable exception from the rule, that any IDisposable should be disposed
after use.

Greetings
Christof

"Bob Weiner" <bo*@engr.uconn.eduschrieb im Newsbeitrag
news:ek**************@TK2MSFTNGP06.phx.gbl...
Hi,

I'm an IT guy who likes to think he can program. I have a generic
question about filestreams.

I'm putting together an application and need to write certain activities
out to a log file. I created a Log class to manage all file operations.

The class has Open, Close, and Record methods. I don't understand how the
FileStream object functions, though. If I create the object with FileMode
= OpenOrCreate and FileAccess = ReadWrite it seems I should be able to
attach/detach a StreamWriter object as necessary.

In fact, it works fine until I close the StreamWriter. When I reopen I
find the the FileStream is no longer writeable.

Is there a simple explanation to correct my misunderstanding of the
FileStream or a good tutorial on how they work that I should read.
Forgive me for not searching more on my own but I'm late for a meeting and
I have to get this code out the door asap.

Thanks, bob

Jan 10 '07 #2
By default, StreamWriter assumes ownership of the stream and calls
Dispose / Close on your behalf. Personally I don't like this, and
prefer the "bool leaveOpen" approach used in the compression classes
to allow either usage. There is a ctor for non-closing writers, but it
is internal. Jon Skeet has a non-closing stream wrapper, but since you
are leaving the stream open, why not just reference the writer instead
of the stream? a writer will still allow the same binary access, while
providing text access. Neither approach will make the file any more
accessible.

Marc
Jan 10 '07 #3
Bob,

When you close the writer it closes the underlying stream that's why it is
no longer writable. My suggestion is to keep and reuse the writer untill you
are done writing; otherwise you need to reopen the file everytime you need
to write.
--
Stoitcho Goutsev (100)

"Bob Weiner" <bo*@engr.uconn.eduwrote in message
news:ek**************@TK2MSFTNGP06.phx.gbl...
Hi,

I'm an IT guy who likes to think he can program. I have a generic
question about filestreams.

I'm putting together an application and need to write certain activities
out to a log file. I created a Log class to manage all file operations.

The class has Open, Close, and Record methods. I don't understand how the
FileStream object functions, though. If I create the object with FileMode
= OpenOrCreate and FileAccess = ReadWrite it seems I should be able to
attach/detach a StreamWriter object as necessary.

In fact, it works fine until I close the StreamWriter. When I reopen I
find the the FileStream is no longer writeable.

Is there a simple explanation to correct my misunderstanding of the
FileStream or a good tutorial on how they work that I should read.
Forgive me for not searching more on my own but I'm late for a meeting and
I have to get this code out the door asap.

Thanks, bob

Jan 10 '07 #4
(my binary comment is incorrect, unless you talk to BaseStream which
could get scrappy with cache/flusing - don't do this).

Agree with Christof - in this case we have (without option) delegated
disposal accountability, so it is a bit of an exception to the "using"
pattern, so long as your writer is itself closed and disposed at some
point.

Marc
Jan 10 '07 #5
Bob Weiner wrote:
I'm an IT guy who likes to think he can program. I have a generic question
about filestreams.

I'm putting together an application and need to write certain activities out
to a log file. I created a Log class to manage all file operations.

The class has Open, Close, and Record methods. I don't understand how the
FileStream object functions, though. If I create the object with FileMode =
OpenOrCreate and FileAccess = ReadWrite it seems I should be able to
attach/detach a StreamWriter object as necessary.

In fact, it works fine until I close the StreamWriter. When I reopen I find
the the FileStream is no longer writeable.
StreamWriter and friends (TextReader and TextWriter descendants) close
the inner stream (the stream they were passed in the constructor) when
they themselves are closed. They do this to compose well with idioms
like this:

using (TextWriter writer = new StreamWriter(File.Open('foo.txt')))
//...

If I were writing a logging class, BTW, I'd be sure to open and close
the file in the logging method, in case of someone forgetting to dispose
the logger and thus close the file (which would lose all the log
messages). Also, it wouldn't hurt to have some synchronization (if
that's necessary; I don't know your details).

E.g.

public class Logger
{
string _logFile;
object _lock = new object();

public Logger(string logFile)
{
_logFile = logFile; // null check etc.
}

public void Log(string message)
{
lock (_lock) // assuming this is the only logger writing to this
// file
using (TextWriter writer = File.AppendText(_logFile))
writer.WriteLine(message);
}
}

There are many other concerns that can come into writing logging
architectures though, so using a prebuilt architecture / module may be
worthwhile.

-- Barry

--
http://barrkel.blogspot.com/
Jan 10 '07 #6
Thanks, great comments!

My program is interactive and will archive (but not delete) batches of users
from an Active Directory. Users will have their accounts disabled, moved to
a special OU, and added to a mail-enabled group (disabled users with mail
forwarding enabled will still recieve mail).

In its current form, the User class (with the archive method) and the Group
class will be the only two that use the Log class. These will run
sequentially in one thread so there is no danger of both trying to write to
the same stream simultaneously. The path to the log file will be a
read-only, static variable in the Log class so there is only one log file.
For now I can just leave the stream open and let it dispose of itself at the
end of all things.

The fact that there is a single stream composed of multilple objects which
was closed by the writer is an important point I didn't know. Also because
a single batch may contain hundreds of users, I may update it to a
mutli-threaded version; I guess that will make locking important.

Seems like I/O should be simple!

thanks all, bob
"Bob Weiner" <bo*@engr.uconn.eduwrote in message
news:ek**************@TK2MSFTNGP06.phx.gbl...
Hi,

I'm an IT guy who likes to think he can program. I have a generic
question about filestreams.

I'm putting together an application and need to write certain activities
out to a log file. I created a Log class to manage all file operations.

The class has Open, Close, and Record methods. I don't understand how the
FileStream object functions, though. If I create the object with FileMode
= OpenOrCreate and FileAccess = ReadWrite it seems I should be able to
attach/detach a StreamWriter object as necessary.

In fact, it works fine until I close the StreamWriter. When I reopen I
find the the FileStream is no longer writeable.

Is there a simple explanation to correct my misunderstanding of the
FileStream or a good tutorial on how they work that I should read.
Forgive me for not searching more on my own but I'm late for a meeting and
I have to get this code out the door asap.

Thanks, bob

Jan 10 '07 #7
For now I can just leave the stream open and let it dispose of
itself at the end of all things.
I wouldn't trust this approach; firstly, objects *never" dispose
themselves; they may get finalized by the GC, but that is not (quite)
the same thing. In fact, finalizers aren't fully guaranteed to run at
all, let alone at a predictable time. My advice: find a point in your
program where you know you are preparing to exit; explicitely Close()
and Dispose() the stream/writer, presumably by a static Close() method
on the Log class. The other option is to look for existing logging
solutions; they may do everything you need (and more) and abstract
away the complexities, including (possibly) tricks like queueing
writes in a producer/consumer pattern to avoid being IO-bound (just
blocked while enqueing).

In the threaded scenario, yes: you will need locking.

Marc
Jan 11 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1445
by: J | last post by:
Is it possible to achieve this without PInvoking?
2
1882
by: Suzanne | last post by:
Hi all, I'm attempting to save images (that are in jpeg format) to a database column of type image. I've read over the Microsoft Knowledge Base articles for this and I can get things working...
4
1644
by: monade | last post by:
Hi, i have a file stream std::ofstream file and some data std::string data to serialize in a performance sensitive code section: file << data << '\n' I know that the data will be flushed when...
6
1608
by: al jones | last post by:
I picked a good project to try to learn to use VS - and up till now everything has worked the way I expect. The code is from a VS.net class, which I picked up on the web, from which I've extracted...
5
2565
by: news.microsoft.com | last post by:
Hello, what is the most performant size for the byte array for reading/writing using 2 filestreams? example code: Dim bytearrayinput(4095) As Byte Dim rdlen As Long = 0 Dim totlen As Long...
2
1110
by: Kristian Frost | last post by:
Silly title, sorry. Anyway, I'm thoroughly confused about the whole new "streams" business and it's very late in my local day, so I wondered if any of you in other parts of the world could solve...
4
2305
by: per9000 | last post by:
Hi python people, I am trying to figure out the best way to encrypt files in python. I've build a small script (see below) that encrypts the ubuntu 7.04 iso file in 2 minutes (I like python :)...
2
2929
by: Elikhom | last post by:
Is there any way to open multiple files concurrently and for example read the first line of each and the do some task with them, then read the second line of all of them and do some task again with...
9
10708
by: cnixuser | last post by:
Hi, I was wondering if someone could give me some general pointers about creating client server applications that would be able to communicate with each other over not just the LAN which I am able...
0
7040
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7080
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6736
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
6908
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5331
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4772
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4478
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1299
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
178
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.