Cannot use local variable before its declared

Why am I getting this error? Can someone please help me fix it? Thanks


        protected void Page_Load(object sender, EventArgs e)
        {
            string line;
            int count = 0;
            StreamWriter writer = new StreamWriter(HttpContext.Current.Request.MapPath("/test/magic - " + DateTime.Today.ToString("MM-dd-yy H-m-s") + ".csv"));
            using (StreamReader reader = new StreamReader(HttpContext.Current.Request.MapPath("/test/test.csv")))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    if (count > 50)
                    {
                        writer.Close();
                        StreamWriter writer = new StreamWriter(HttpContext.Current.Request.MapPath("/test/magic - " + DateTime.Today.ToString("MM-dd-yy H-m-s") + ".csv"));
                        count = 0;
                    }
                    writer.WriteLine(line);
                    count++;
                }
            }
            writer.Close();
        }

You are re-declaring writer, try the following:

                    
if (count > 50)
{
   writer.Close();
   writer = new StreamWriter(HttpContext.Current.Request.MapPath("/test/magic - " + DateTime.Today.ToString("MM-dd-yy H-m-s") + ".csv"));
   count = 0;
}

You might find that this runs too quickly for it to generate unique filenames though…

Oh wow cant believe I missed that! I have another question. With the above code, it inserts a blank line after the last record. Is it possible for it not to do that?

Check whether line is null or empty. This should do the trick

while (line = reader.ReadLine() && !String.IsNullOrEmpty(line))