Possible Duplicate:
The file is being used by another process, I must close it? How?
I’m not sure why is that but I cannot write some data into text file. I am doing like so:
private void CreateLastOpenFile()
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (!File.Exists(file))
{
FileStream newFile = File.Create(file);
newFile.Close();
}
using (StreamWriter lastOpenedFile = new StreamWriter(file))
{
lastOpenedFile.WriteLine(filePath);
}
}
Am I doing this correctly?Should I be checking if directory exists? If file exists? What’s the proper way? I was using examples from MSDN but I’m not sure how to do this.
I’d rather do:
This creates a new file if it doesn’t exist.
usingautomatically callsDisposeon the writer, which in turn callsClose, which closes both writer and the underlying stream.