First - it's hard to help you debug if we don't know what you're expecting and what behavior you are observing.

General thoughts though:

(1) Call StreamWriter.Close() afterward
(2) What's with the @ in outfilename=@tempfilename. That is unusual syntax and probably unnecessary (to the extent that I wasn't even sure it was syntactically legal without checking).

My preferred method of doing this is to buffer everything first and then do one disk IO event:

Code:
System.Text.StringBuilder outData = new System.Text.StringBuilder();
for(int p; ...)
{
    for(int q; ...)
    {
        outData.Append("your data here");
    }
    outData.AppendLine(); //New line at end of row
}

System.IO.File.WriteAllText(outfileName, outData.ToString()); //Write to disk