I’m trying to find out if a file exists, if it does, verify if the css style already exists, if not, write them at the end of the file …
I’m doing all this already but in 3 steps:
Does the file exist?
FileInfo fi= new FileInfo(Path.Combine(rootPath, "DefaultStyles.css");
If it does, I use TextReader to get the contents
using (TextReader tr = new StreamReader(file))
{
r = tr.ReadToEnd().Contains(".onebyonecard");
tr.Close();
}
Then I write into it if style was not found
using (TextWriter tw = new StreamWriter(file))
{
tw.Write(cssStyle);
tw.Close();
}
Is there a way to do this in one easy open / close, instead needed to open the file over and over?
Well you can open a single stream for read and write – but given that you’re reading the whole file, I would personally just open it twice. Note that your current code will overwrite the file, not append to it.
I would personally use the static methods in the
Fileclass:This is simpler than having a read/write stream and creating both a
TextReaderand aTextWriterover it.A couple of notes: