title: Query LOCAL Bitcoin blockchain with C# .NET
body: <p>I am trying to check the <strong>balance</strong> of a given Bitcoin address by using <strong><em>ONLY</em></strong> the locally stored blockchain (downloaded via Bitcoin Core). Something similar to this (by using NBitCoin and/or QBitNinja), but without needing access to the network:</p>
  
  <pre><code>private static readonly QBitNinjaClient client = new QBitNinjaClient(Network.Main);
  
  public decimal CheckBalance(BitcoinPubKeyAddress address)
  {
      var balanceModel = client.GetBalance(address, true).Result;
      decimal balance = 0;
  
      if (balanceModel.Operations.Count &gt; 0)
      {
          var unspentCoins = new List&lt;Coin&gt;();
          foreach (var operation in balanceModel.Operations)
              unspentCoins.AddRange(operation.ReceivedCoins.Select(coin =&gt; coin as Coin));
          balance = unspentCoins.Sum(x =&gt; x.Amount.ToDecimal(MoneyUnit.BTC));
      }
      return balance;
  }
  </code></pre>
  
  <p>The example above needs access to the network. I need to do the same thing offline. I came up with something like this, but obviously it doesn't work:</p>
  
  <pre><code>public decimal CheckBalanceLocal(BitcoinPubKeyAddress address)
  {
      var node = Node.ConnectToLocal(Network.Main);
      node.VersionHandshake();
      var chain = node.GetChain();
  
      var store = new BlockStore(@"F:\Program Files\Bitcoin\Cache\blocks", Network.Main);
  
      var index = new IndexedBlockStore(new InMemoryNoSqlRepository(), store);
      index.ReIndex();
  
      var headers = chain.ToEnumerable(false).ToArray();
  
      var balance = (
          from header in headers
          select index.Get(header.HashBlock) 
          into block
          from tx in block.Transactions
          from txout in tx.Outputs
          where txout.ScriptPubKey.GetDestinationAddress(Network.Main) == address
          select txout.Value.ToDecimal(MoneyUnit.BTC)).Sum();
  
      return balance;
  }
  </code></pre>
  
  <ol>
  <li>It hangs during the query</li>
  <li>I want something instead of <code>InMemoryNoSqlRepository</code> to be stored in a file in order to prevent using <code>ReIndex()</code> which slows everything down</li>
  </ol>
  
  <p>My requirement is to <strong><em>Check Balance</em></strong> the same way as in the first method but by querying blocks stored on my disk.</p>
  
  <p>Actually what I require might just be an answer to <a href="https://bitcoin.stackexchange.com/questions/50817/how-to-run-qbitninja-server-locally">this question</a>: </p>