private void WriteSeparateCodeFiles()
{
// Some assertions to make debugging easier.
Debug.Assert(!string.IsNullOrEmpty(options.OutputLocation), "This action cannot be performed when output location is null or an empty string.");
codeFilesCount = codeNamespace.Types.Count;
// Initialize the file names array to hold enough all our type names.
generatedCodeFileNames = new string[codeFilesCount + textFiles.Count];
// Itterate the the CodeTypeDeclaration types in the codeNamespace and
// generate a file for each of them.
for (int i = 0; i < codeNamespace.Types.Count; i++)
{
// Take a reference to the CodeTypeDeclaration at the current index.
CodeTypeDeclaration ctd = codeNamespace.Types[i];
// Create a temporary CodeNamespace.
CodeNamespace tempns = new CodeNamespace(codeNamespace.Name);
// Add the type to the temporary namespace.
tempns.Types.Add(ctd);
// Get the destination file name.
string fileName = CodeWriter.GetUniqueFileName(options.OutputLocation, ctd.Name, options.Language, options.OverwriteExistingFiles);
// Create a StreamWriter for writing to the destination file.
StreamWriter writer = new StreamWriter(fileName);
try
{
// Write out the code to the destination file.
provider.GenerateCodeFromNamespace(tempns, writer, codeGenerationOptions);
// Flush all buffers in the writer.
writer.Flush();
// Finally add the file name to the generated file names array.
generatedCodeFileNames[i] = fileName;
}
catch (IOException e)
{
// Wrap the IOException in a CodeWriterException with little bit
// more information.
throw new CodeWriterException(
string.Format("An error occurred while trying write to file {0}: {1}", fileName, e.Message), e);
}
finally
{
// No matter what happens, dispose the stream writer and release the unmanaged
// resources.
writer.Dispose();
}
}
}