Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I,m getting error(object reference not set to an instance of an object) when i try to add file names to list

button1_click--- for getting the folder path to textbox1
button2_click--- for storing filenames to list
button3_click--- for saving filenames to report.txt
C#
public partial class Form1 : Form
{
    List<string> fileStore = null;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
    
        folderBrowserDlg.ShowNewFolderButton = true;
      
        DialogResult dlgResult = folderBrowserDlg.ShowDialog();
        if (dlgResult.Equals(DialogResult.OK))
        {
        
            textBox1.Text = folderBrowserDlg.SelectedPath;
           
            Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
         DirectoryInfo dir1 = new DirectoryInfo(textbox1.text);
        FileInfo[] files = dir1.GetFiles("*.*", SearchOption.AllDirectories);
        
        try
        {
            foreach (FileInfo f in files)
            {

                fileStore.Add(f.Name.ToString());

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }  
    }

    private void button3_Click(object sender, EventArgs e)
    {
        const string sPath = "report.txt";

        System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
      
        foreach (string item in fileStore)
        {
             SaveFile.WriteLine(item.ToString());
        }
        
        SaveFile.Close();

        MessageBox.Show("Programs saved!");
    }
}


[Edit member="Tadit"]
Urgency removed.
Corrected formatting and/or grammatical issues.
[/Edit]
Posted
v3
Comments
ConnectingKamlesh 22-May-15 6:35am    
On which line are you getting that error ?

1 solution

Probably you need to initialize your "fileStore" variable like this :

List<string> fileStore = new List<string>();
 
Share this answer
 
Comments
Praveen Kumar Upadhyay 25-May-15 5:37am    
Yes, very true. +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900