0

I'm hoping to have a simple function (not a class or library) that lets me dump information to a text file as I'm executing, but easier said than done. There are plenty of questions about stream writers, but somehow none of them are doing what I'm looking for:

    public partial class MainWindow : Window
    {
        // Make true for logging
        private bool diag = true;
        private StreamWriter logger = null;

        public MainWindow()
        {
            logger = new StreamWriter(regStuff.MyDocsPath() + @"\Paneless\log.txt");
        }

        private void Log(string toLog)
        {
            if (diag)
                logger.WriteLine(toLog);
        }
    
    }

In theory, with the above, I should be able to call "Log" with a string at any point in my code to have it dump a bit of diagnostic code to the text file. It doesn't work and I can't figure out why. From the guides, this seems correct. I've seen some that use a "using" statement, but do I really want to have a hundred of those one after the other? Seems... inefficient.

not_a_generic_user
  • 1,906
  • 2
  • 19
  • 34
  • Save yourself the headaches and time and just use a Logging Framework. – Fildor Mar 23 '22 at 13:22
  • `...but somehow none of them are doing what I'm looking for`. You want to use a streamwriter to write to a file. A bit hard to believe that there are no guides on that. – Jonesopolis Mar 23 '22 at 13:27
  • Maybe this helps you: https://stackoverflow.com/a/7306243/4921129 – Fabio Cavallari Mar 23 '22 at 13:39
  • Unrelated: `regStuff.MyDocsPath() + @"\Paneless\log.txt"` - you may consider using [`Path.Combine`](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-6.0) – Fildor Mar 23 '22 at 13:43
  • ^^ But really: use a Framework. `private bool diag = true;` - you surely do not want to recompile and redeploy everytime you need to switch logging on/off?? – Fildor Mar 23 '22 at 13:52
  • A framework might be superior, but it's also a heavy lift in learning how it works, making sure it doesn't cause unwanted behavior with my code and so on. I'll consider it if there's no simple way to write output to a file - unless you're telling me C# can't actually do that. – not_a_generic_user Mar 24 '22 at 14:00

0 Answers0