I have a class where you open the console, show some data and then close, when executing a second time (without closing the program), an exception occurs in Console.WriteLine("")
- If run once, everything works
- If you close and open the program again, everything works.
- If you try to run the
ExportarArquivos()
routine twice, without closing the application before the following error occurs:
Error: Invalid handle.
StackTrace:em System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) em System.IO.__ConsoleStream.Write(Byte[] buffer, Int32 offset, Int32 count) em System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) em System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count) em System.IO.TextWriter.WriteLine(String value) em System.IO.TextWriter.SyncTextWriter.WriteLine(String value) em System.Console.WriteLine(String value)'
Class:
public static class Exportar
{
[DllImport("kernel32.dll")]
static extern bool AllocConsole();
[DllImport("kernel32.dll")]
static extern bool FreeConsole();
public static void ExportarArquivos()
{
bool aux = AllocConsole();
Console.WriteLine(""); //ocorre a exceção aqui (na segunda vez), e aux == true neste ponto.
Console.WriteLine("Gerando arquivos...");
//Trabalha um pouco
Console.WriteLine("");
Console.WriteLine("Pressione qualquer tecla para sair");
Console.ReadKey();
FreeConsole();
}
}
Does anyone know what might be causing this?