The other day, I was working on how to create files on the fly(dynamically create any file of any extension like .doc, .txt etc.). To do this, we will first have to provide an editor like rich text box where the user can type in something and when he saves,a dynamic file is created which is saved in the document library.
I used a FCK editor in this case.

I intended to save other meta data along with the file in the document library(will talk about it later in this article).

string strRTFFileName = string.Empty;
SPList ospList = null;
Hashtable metadataTable = new Hashtable();
MemoryStream mstream = new MemoryStream();
Stream stream = null;
SPWeb ospWeb = ospSite.OpenWeb();
string strReader = string.Empty;
SPWeb sourceWeb = SPContext.Current.Web;
string sourceList = “Brochure”; //Name of Document library to save file.
SPList sourceListObj = sourceWeb.Lists[sourceList];

//Declare a streamwriter and output it’s value to memory stream
StreamWriter sw = new StreamWriter(mstream);
//FCKeditor1 is name of the FCK Editor.
sw.Write(FCKeditor1.Value);
// Creating file name dynamically based on datetime value

strRTFFileName = string.Format(“text-{0:yyyy-MM-dd_hh-mm-ss-tt}.rtf”, DateTime.Now);
string pattern = “[^a-z0-9A-Z. ]”;
Regex objRegex = new Regex(pattern);
strRTFFileName = objRegex.Replace(strRTFFileName, “”);

// End of dynamic file name creation

// On flushing StreamWriter, value is copied to memorystream.
sw.Flush();
byte[] contents = new byte[mstream.Length];
mstream.Read(contents, 0, (int)mstream.Length);

ospWeb.AllowUnsafeUpdates = true;
sourceItem = sourceWeb.Files.Add(sourceWeb.Url + “/” + sourceListObj.RootFolder.ToString() + “/” + strRTFFileName, mstream, true);
mstream.Close();
ospWeb.AllowUnsafeUpdates