File.Create()

  • Thread starter Thread starter Jeremy McPeak
  • Start date Start date
J

Jeremy McPeak

I have a quick question about using File.Create().

I have this code:

FileStream cacheFile = File.Create(fileName);
StreamWriter strmWriter = new StreamWriter(cacheFile);
strmWriter.Write(stringToWrite);
strmWriter.Close();
cacheFile.Close();

I'm a lazy mofo, and I'm always looking to cut as many lines as possible. I
am a self-taught programmer, so I am not too familiar what is the proper way
things are done. Would the following lines be a suitable replacement for
the above code? If not, please tell me why =)

StreamWriter strmWriter = new StreamWriter(File.Create(fileName));
strmWriter.Write(stringToWrite);
strmWriter.Close();


Thanks a bunch.
 
Jeremy,

The easiest way to do this would be to do the following:

// Create the file.
using (StreamWriter strmWriter = new StreamWriter(fileName))
{
// Write the line.
strmWriter.Write(stringToWrite);
}

If you pass a string to the constructor of the StreamWriter, then it
will create the file for you if it doesn't exist (or overwrite it if it
does), using the default encoding. Also, placing it in the using statement
will cause the stream writer to be disposed of properly (as well as the
underlying stream).

Hope this helps.
 
Back
Top