As long as you are in status, get accepted in school, get an I-20 in which the program starts before the expiration of your current status, you can apply for COS from B2 to F1.
There is no legal prohibition although there are some hurdles. Make sure you maintain lawful status as you go to the process. Speak with your designated school official. The US consulate may believe that you obtained a B and really had the intent to come to United States as a student which may cause you issues in the future.
Attorney Robert Brown's (former INS Director, 1972-99) reply to your question is general in nature, and does not constitute legal advice as all facts are known to him. For specific advice or representation you should retain an attorney experienced in immigration law. Mr. Brown's reply on AVVO does not create an attorney/client relationship not constitute legal advice.
Always better to apply for an F-1 visa abroad, but if you have been present in the US for 60 days or more, you can apply for a change of status.
Mr. Shusterman's (former INS Trial Attorney, 1976-82) response to your question is general in nature, as not all the facts are known to him. You should retain an attorney experienced in immigration law to review all the facts in your case in order to receive advice specific to your case. Mr. Shusterman's statement above does not create an attorney/client relationship.