0

I am trying to learn C# and ADO.NET using this book: 'Accesing Data with Microsoft .NET Framework 4' by Glenn Johnson. In the third chapter, 'Introducing to LINQ', there is this code snippet:

foreach (var color in results)
{
    txtLog.AppendText(color + Environment.NewLine);
}

Since there are no details of how to create the txtLog file, I tried to do it this way:

StreamWriter txtLog=File.CreateText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"txtLog.txt"));
            foreach (var color in results)
                txtLog=File.AppendText(color + Environment.NewLine);

The problem is Environment.NewLine throws me an error: 'Illegal charactes in path'. After that, I learned that AppendText method takes as argument a path, which pretty much confuses me. How am I supposed to make the code from the book work? The snippet is used multiple times. Thanks.

Tanatos Daniel
  • 558
  • 2
  • 9
  • 27
  • `File.AppendText` does not use `txtLog`, try `txtLog.WriteLine` instead. – Lasse V. Karlsen Jul 30 '14 at 09:24
  • Are you looking for [File.AppendAllText](http://msdn.microsoft.com/library/ms143357.aspx) - "Appends the specified string to the file, creating the file if it does not already exist." – Corak Jul 30 '14 at 09:31
  • I read ahead and from a point, `txtLog.Writeline` is used instead. But what's with `txt.AppendText`? Why is it used like that? Or it's just a mistake someone forgot to correct? – Tanatos Daniel Jul 30 '14 at 09:34

2 Answers2

1

Well, if you use Windows Forms you can create a new TextBox with the name txtLog. You can see here how to create one.

Then your code will execute just fine without other modifications.

Panayotis
  • 1,743
  • 1
  • 17
  • 30
  • Your suggestion did solve the problem. But for the `Environment.NewLine` to work, a `RichTextBox` must be used instead. Thanks! – Tanatos Daniel Jul 30 '14 at 09:40
0

You could use a FileStream to create/append to the file, then a StreamWriter to write to that stream. For example:

    using (FileStream stream = new FileStream("C:\\Path\\FileName.txt", FileMode.Append, FileAccess.Write))
    {
        using (StreamWriter sw = new StreamWriter(stream))
        {
            sw.WriteLine("Your message");
        }
    }

This will create the file if it doesn't exist & append to it if it does exist.

Craig
  • 738
  • 7
  • 9