-1

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 ?

JumpingJezza
  • 5,498
  • 11
  • 67
  • 106
Chlebta
  • 3,090
  • 15
  • 50
  • 99
  • 1
    Is there any particular reason you are redirecting the console just to write to the file? `StreamWriter` has methods for writing strings that look just like the `Console` object. IMO there is no need here to redirect the Console and use `Console.WriteLine` unless you have other parts of your program that use `Console.WriteLine` that you sometimes need to direct to a file. – Los Frijoles May 18 '14 at 22:09

1 Answers1

1

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.

Los Frijoles
  • 4,771
  • 5
  • 30
  • 49
  • It work but i get only the last line writed I think in each call he's delete file content and write the new content only – Chlebta May 18 '14 at 22:20
  • Ok, in that case, replace both `using` lines with: `using(var sw = File.AppendText(fileName))` (two `using` statements are replaced by just one). The [`File.AppendText`](http://msdn.microsoft.com/en-us/library/system.io.file.appendtext(v=vs.110).aspx) static method takes care of both opening the file and making sure it is in append mode. This will keep the existing file content while appending new content. Is that what you wanted to accomplish? – Los Frijoles May 18 '14 at 22:23
  • Trying to change this I got `Cannot open Redirect.txt for writing` error – Chlebta May 18 '14 at 22:28
  • A couple questions: Does it work on the first call, but not the second? Does your process have permission to access the file? Is it locked by another process? – Los Frijoles May 18 '14 at 22:30
  • Yes it's dosn't work for the second call but the first fine, and I sloved it like this see my edit – Chlebta May 18 '14 at 22:37
  • Permissions either are currently or will become a problem. Applications do not, under normal conditions, have permission to write to files in the root directory of the disk. You need to move `redirect.txt` somewhere more reasonable, like into a subdirectory of your Users folder. @chlebeta – Cody Gray - on strike May 18 '14 at 23:09