views:

59

answers:

2

if i try to add below data to any text file Error occyred: "NullReferenceException was unhandled." Error occurs in Tex.Writeline(li) . . . .

Detail: Object reference not set to an instance of an object.

  public void WriteScript(List myTextList)
        {
            FileInfo f = new FileInfo(@"C:\temp\Scripts.txt");
            StreamWriter Tex = null;
            if(!f.Exists)
                f.CreateText();
            else
                f.AppendText();
            foreach (string li in myTextList)
            {
                Tex.WriteLine(li);
                Tex.Write(Tex.NewLine);
                Tex.WriteLine("GO");
                Tex.Write(Tex.NewLine);
            }
                Tex.Close();
                Tex.Dispose();

        }
Create table ENG_PREP (ENG_PREP_ID integer PRIMARY KEY identity(1,1), [ENG_PREP_MPD_REFERENCE]  nvarchar(3000) , [ENG_PREP_TASK_DESCRIPTION]  nvarchar(3000) , [ENG_PREP_ZONE]  nvarchar(3000) , [ENG_PREP_SUBZONE]  nvarchar(3000) , [ENG_PREP_PREPERATION_NO#]  nvarchar(3000) , [ENG_PREP_PREPERATION_DESCRIPTION]  nvarchar(3000) , [ENG_PREP_RELATED_PREPERATION]  nvarchar(3000) , [ENG_PREP_OPEN_MH]  nvarchar(3000) , [ENG_PREP_CLOSE_MH]  nvarchar(3000) , [ENG_PREP_ESTIMATED_MH]  nvarchar(3000) , [ENG_PREP_CREW_DONE]  nvarchar(3000) , [ENG_PREP_SKILL_DONE]  nvarchar(3000) , [ENG_PREP_MAINTENANCE_DATA]  nvarchar(3000) , [ENG_PREP_EFF_A/C]  nvarchar(3000) , [ENG_PREP_EFF_ENG]  nvarchar(3000) , [ENG_PREP_NOTE]  nvarchar(3000) , [ENG_PREP_REFERENCE]  nvarchar(3000) , [ENG_PREP_ESTIMATED_MH2]  nvarchar(3000) , [ENG_PREP_MH]  nvarchar(3000) , [ENG_PREP_CONTROL]  nvarchar(3000)  )
+6  A: 

You are not initializing the Tex variable, so you are basically doing:

null.WriteLine(li);

and there's your NullReferenceException

SWeko
@Shimrod, the declaration `StreamWriter Tex = null;` kinda blows that out of the water.
Lazarus
I deleted my comment, didn't read correctly, you are completely right.
Shimrod
+2  A: 

Change your lines

 if(!f.Exists)
     f.CreateText();
 else
     f.AppendText();

by

  if(!f.Exists)
     Tex =  f.CreateText();
  else
      Tex =  f.AppendText();

or by

 using(StreamWriter Tex = f.Exists?f.AppendText():f.CreateText())
 {
        ...
 }
Gregoire