Realizing basic semiconductor devices such as p-n junctions are necessary for developing thin-film and optoelectronic technologies in emerging planar materials such as MoS2. In this work, electrostatic doping by buried gates is used to study the electronic and optoelectronic properties of p-n junctions in exfoliated MoS2 flakes. Creating a controllable doping gradient across the device leads to the observation of the photovoltaic effect in monolayer and bilayer MoS2 flakes. For thicker flakes, strong ambipolar conduction enables realization of fully reconfigurable p-n junction diodes with rectifying current-voltage characteristics, and diode ideality factors as low as 1.6. The spectral response of the photovoltaic effect shows signatures of the predicted band gap transitions. For the first excitonic transition, a shift of >4kBT is observed between monolayer and bulk devices, indicating a thickness-dependence of the excitonic coulomb interaction. Two-dimensional (2-D) crystalline materials have attracted a significant amount of research efforts since the isolation of graphene by micromechanical exfoliation [1,2,3,4]. They show promise in novel electronic and optoelectronic applications, where the low-dimensionality provides ideal electrostatic control for field-effect transistor devices, or large area-to-volume ratio for sensors and photoelectric devices. Among 2-D crystals, MoS2, a transition metal dichalcogenide (TMDC), has received particular attention as channel material for thin-film or flexible electronics [5,6,7] because its mobility is considerably higher than amorphous or polycrystalline materials, and because it can be used in various heterostructures to enable diverse electronic applications [8,9,10,11,12].The most remarkable attributes of MoS2 lie in its bandstructure, which shows a crossover from an indirect bandgap (~1.3 eV) in bulk to a direct one (~1.9 eV) for a monolayer [13,14]. In the monolayer form, MoS2 has been used in optoelectronics [15,16,17], and has been investigated to enable a new class