The hearing was a chance for Mr. Wray, 50, a private lawyer and former top Justice Department prosecutor, to demonstrate that he was the person to lead the nation’s premier law enforcement agency under extraordinary circumstances. Many of the questions from senators centered on how he would deal with Mr. Trump, referring to Mr. Comey’s tense interactions with the president.

Senator Patrick J. Leahy, Democrat of Vermont, asked what Mr. Wray would do if the president requested that he take any steps that Mr. Wray believed were illegal.

“First, I would try to talk him out of it,” Mr. Wray said. “If that failed, I would resign.”

He also said he had no doubts about the intelligence community’s assessment that Russia interfered in the election, a conclusion the president has questioned. He pledged that if confirmed, he would read the classified portions of the assessment as soon as he was sworn in.

Mr. Wray also sought to separate himself from Mr. Comey’s actions, including the former director’s announcement last summer that he would not recommend charges in the investigation of Hillary Clinton’s handling of classified information. Mr. Comey had explained the move as an effort in part to maintain the F.B.I.’s political neutrality, but he was widely criticized for plunging the bureau into the middle of the presidential campaign. Former prosecutors criticized him for making public remarks about Mrs. Clinton’s behavior.

Pressed by Senator Lindsey Graham, Republican of South Carolina, on how he would have handled the investigation, Mr. Wray said he would not have held a news conference.