title: SharePoint 2007 : How to programmatically upload binary file into Document Library?
body: <p>I encounter a problem to programmatically create an item into Document Library in SharePoint 2007.</p>
  
  <p>Below is my code fragment, perhaps you might able to point out what is my error:</p>
  
  <pre><code>SPSecurity.RunWithElevatedPrivileges(delegate()
  {
      using (SPSite site = new SPSite(_url))
      {
          using (SPWeb web = site.OpenWeb())
          {
              SPList customList = web.Lists["Test1"];
              foreach (SPListItem ltItem in customList.Items)
              {
                  if (ltItem.Attachments != null &amp;&amp; ltItem.Attachments.Count &gt; 0)
                  {
                      //Get Test1 File Collection
                      SPFolder folder = web.GetFolder(ltItem.Attachments.UrlPrefix);
                      SPFileCollection fileColl = folder.Files;
  
                      //Get binary data of attachment
                      SPFile file = ltItem.ParentList.ParentWeb.GetFile(ltItem.Attachments.UrlPrefix + ltItem.Attachments[0]);
                      byte[] fileData = file.OpenBinary();
  
                      //Get Relative URL of attachment destination
                      string destFile = fileColl.Folder.Url + "/" + file.Name;
  
                      web.AllowUnsafeUpdates = true;
                      //Add attachment into Document Library
                      SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test2"];
                      SPFile file2 = docLib.RootFolder.Files.Add(destFile, fileData, true);
                      file2.Item.Update();
                      web.AllowUnsafeUpdates = false;
                  }
              }
          }
      }
  });
  </code></pre>
  
  <p>I hit "Object reference not set to an instance of an object" at this link of code file2.Item.Update();</p>
  
  <p>Thank you in advanced.</p>