Kishor
Kishor

Reputation: 29

Inaccessible file

The following line enables me to access my results file:

// Write the string to a file.
public System.IO.StreamWriter file = new System.IO.StreamWriter
("C:\\TestDev\\Visual Stidio 2012 Developments\\Training\\Project   
1\\HSMTESTClient_03\\HSMTESTClient\\Results\\Results.txt");

After that I utilize the following to write to my file:

      file.WriteLine(" TX: " + message + "\r\n");

All is OK. However in this development (encryption/decryption program) I have managed to embed another project called SafeNetAdaptor. All attempts to write to the my Results file have so far failed. I need to be able to log results from various operation during this very complicated process. To cotinue with the debug I was prepared to create a different Results file for that part - however, although the file was created, no results were written to it. Why is this so? Thanks for your assistance & consideration.

Upvotes: 1

Views: 209

Answers (2)

Luaan
Luaan

Reputation: 63722

public System.IO.StreamWriter file

Just screams "BAD" to me.

Sharing access to a file via a public field? Bad idea. You want to provide encapsulation. You ideally want to provide disposal semantics. You need to handle buffering. You want to be independent of actual implementation - instead of a public StreamWriter, expose a logging class (and as Stefano wrote, you'd usually use a ready logging framework).

StreamWriter requires manual flushing, it doesn't write as soon as you do. Even flushing the StreamWriter doesn't guarantee anything, because it can still be in the write buffers - I/O operations are pretty much never done directly to the device. Also, flushing after every log attempt will make your performance suffer - not very good, since logging should have as little impact on performance as possible.

And don't forget to properly close the file when you're done. Ideally, if you only handle logging for a sub-operation, simply wrap the whole thing in a using:

using (var file = File.CreateText("results.txt"))
{
  var log = new MyLoggingManager(file);

  DoStuff(log);
}

There's tons of other problems that can appear, related to file sharing, permissions, concurrent access and many more. Just use a logging framework :)

Upvotes: 0

Stefano Altieri
Stefano Altieri

Reputation: 4628

Not a good idea :)

Consider using a logging framework. There are plenty around. Examples are

Upvotes: 1

Related Questions