Search code examples
c#console-applicationfilewriter

Console write in file issue


This is my function to write in file :

FileStream file = new FileStream ("c:/Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);
public void writeFile(string line, FileStream file) 
{
    StreamWriter writer;
    TextWriter oldOut = Console.Out;
    try
    {
        writer = new StreamWriter(file);
    }
    catch (Exception e)
    {
        Console.WriteLine("Cannot open Redirect.txt for writing");
        Console.WriteLine(e.Message);
        return;
    }
    Console.SetOut(writer);
    Console.WriteLine(line);
    Console.SetOut(oldOut);
    writer.Close();
    file.Close();
    Console.WriteLine("Done");
}

And this how I use it :

writeFile("********* Clienta *********",file);
writeFile("Centre   ***  " + id,file);

But when I run my code I got this error :

Cannot open Redirect.txt for writing
The stream can not be written.

What's wrong in my code ?


Solution

  • Your problem is that you are closing the filestream twice. After your first call completes, you have closed the file and so when you call the second time, it tries to create a streamwriter on a closed filestream.

    Remove the file.Close and change your argument type to StreamWriter. Create your streamwriter outside the function and thn when you are finished writing files, close that.

    Try something like this:

        public void WriteFile(string line, string fileName)
        {
            try
            {
                using (var sw = new StreamWriter(fileName, true))
                {
                    sw.WriteLine(line);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Cannot open Redirect.txt for writing");
                Console.WriteLine(e.Message);
                return;
            }
    
            Console.WriteLine("Done");
        }
    

    Now, instead of passing in your filestream to your function, pass in your C:/Redirect.txt:

    WriteFile("********* Clienta *********","C:/Redirect.txt");
    WriteFile("Centre   ***  " + id, "C:/Redirect.txt");
    

    I would note: this is very sub-optimal. Opening and closing a file for each and every call to this function is quite inefficient. The better way to do this would be to have an object that writes the messages to your files which keeps track of your StreamWriter and FileStream and then pass that object around so that you only open the file once and close the file once. If it's a long running program, you would make one of these objects for each "unit of work" (a request, periodic interrupt, whatever). However, that isn't what you asked for.