Why do I get the above error message when I use using (fileStream = new FileStream(path, FileMode.Append, FileAccess.Write)), but the program works fine when I replace it with fileStream = File.Create(path);?
I want to add console output to an external file. Here is my code:
class ConsoleCopy : IDisposable
{
FileStream fileStream;
StreamWriter fileWriter;
TextWriter doubleWriter;
TextWriter oldOut;
class DoubleWriter : TextWriter
{
TextWriter one;
TextWriter two;
public DoubleWriter(TextWriter one, TextWriter two)
{
this.one = one;
this.two = two;
}
public override Encoding Encoding
{
get { return one.Encoding; }
}
public override void Flush()
{
one.Flush();
two.Flush();
}
public override void Write(char value)
{
**one.Write(value);**
two.Write(value);
}
}
public ConsoleCopy(string path)
{
oldOut = Console.Out;
try
{
**
fileWriter = new StreamWriter(fileStream);
fileWriter.AutoFlush = true;
doubleWriter = new DoubleWriter(fileWriter, oldOut);
}
catch (Exception e)
{
Console.WriteLine("Cannot open file for writing");
Console.WriteLine(e.Message);
return;
}
Console.SetOut(doubleWriter);
}
public void Dispose()
{
Console.SetOut(oldOut);
if (fileWriter != null)
{
fileWriter.Flush();
fileWriter.Close();
fileWriter = null;
}
if (fileStream != null)
{
fileStream.Close();
fileStream = null;
}
}
}
I call this method in my main method as such:
using (var cc = new ConsoleCopy("mylogfile.txt"))
{
DateTime theDate = DateTime.UtcNow;
string custom = theDate.ToString("d");
Console.WriteLine("User has logged in on " + custom);
}
UPDATE:
The error was previously shown on one.Write(value). I managed to solve this, though thanks to Peter. Thank you all for your contribution and help :)
source
share