Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 297
  • Last Modified:

I/O operations.



Hi group, I want to write to a file when an exception ocurs,
I use the FilseStream and StreamWrite classes.

This is the code:
//Creates the FileStream and StreamWrite object
..............
if (File.Exists(fileName))

{

fs = new FileStream(fileName,FileMode.Open,FileAccess.Write);

sw = new StreamWriter(fs);


}

else

{

fs = new FileStream(fileName,FileMode.Create);

sw = new StreamWriter(fs);

.......................

.......................
//The code that writes into a file
try

{

//buffer the string that I want to write

sw.Write(buffer);

}

catch(Exception e)

{

return;

}

It's seems to work but doesn't write anything in the file.
0
alarcia
Asked:
alarcia
  • 2
2 Solutions
 
Nebulus_Commented:
I think that you must flush the StreamWriter. This can be done automatically after you create the sw object:

sw.AutoFlush = true;

or manually:

sw.Flush();

after each write op.
0
 
CEILIDHCommented:
One additional point;

your first if-statement to create a new FileStream is not actually necessary, since the FileMode 'Create' will create a new file if is does not exists, or open the file if it does exist.

You are also not specifiying a FileAccess parameter for your second FileStream, so be sure to check what the Default Access is, since it may be 'Read', and you want to 'Write'.

Good luck.
0
 
AvonWyssCommented:
Try it like this:

               using (StreamWriter sw=new StreamWriter(new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write), true)) {
                    sw.Write(buffer);
               }

Notes:
- the "using" clause will have the compiler close and dispose the StreamWriter automatically (and therefore also the underlying stream).
- FileMode.Create always deletes an existing file, but OpenOrCreate opens the file if it exists and creates it otherwise.
- The "true" parameter will make sure that data will be appended instead of overwriting existing data in the file.
0
 
AvonWyssCommented:
Even easier...

               using (StreamWriter sw=new StreamWriter(fileName, true)) {
                    sw.Write(buffer);
               }
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now