Hi,
>In my C# project I am writing a bunch of strings into a file and I am using StreamWriter. I want to do three things that I can't figure out how to do.
>One, I need to count the number of strings I write to the file. I am using i++ after every call to sw.write but I would like to have the call itself do the i++ so I don't have to remember do it and have to look at a million i++s.
>Two, I want to be able to optionally terminate the string with a carriage return for debugging but have no carriage returns in the production file.
>Three, I would like to open the StreamWriter in my Main method and be able to call sw.write from other methods. In other words, I would like to have subroutines to build the strings in chunks but not have to return to the Main to write them, only return to the main when I need to call the next subroutine (and I don't want to have to open and close the streamWriter a thousand times. Otherwise I will end up with one big ol' honking long program that will be hard to read and maintain....)
>Obviously a c# lightweight here. Thanks in advance for any help you can give me.
Two suggestions:
(a) Sub-class
public class MyStringWriter : System.IO.StringWriter
{
int _hits = 0;
public override void WriteLine(string s)
{
_hits++;
#if (DEBUGGING)
base.WriteLine(s);
#else
base.Write(s);
#endif
}
public int Hits
{
get { return _hits; }
}
}
(b) Use a static wrapper
public static class MyStringWriterWrapper
{
static System.IO.StringWriter sw = new System.IO.StringWriter();
static int _hits = 0;
public static void WriteLine (string s)
{
_hits++;
#if (DEBUGGING)
sw.WriteLine(s);
#else
sw.Write(s);
#endif
}
If you use the second you get automatic global access (providing there's a reference to the DLL) - just use MyStringWriterWrapper.WriteLine() wherever you need it - but you'll need to add code to access other methods/properties of the actual Stringwriter. If you sub-class you'll need to create an instance with global scope...
HTH,
Viv