AppendText method in C# (Windows Forms)
-
21-12-2019 - |
Question
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.
Solution
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.
OTHER TIPS
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.