Creating sprite in code using TextureImporter with C#?

I’m trying to create a Sprite based on an external texture. The intended functionality once I finish is that a user would be able to select a photo from an external source and use that as their sprite. My problem is trying to convert that texture into a sprite, which so far I haven’t been able to do.

using UnityEngine;
using UnityEditor;

public Material defaultMaterial; //prefab material set already
IEnumerator Start()
{

SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
string path = "file://C:\\Users\\i5\\Documents\\My2DProject\\Assets\\oranges.png";

TextureImporter tImport =  AssetImporter.GetAtPath(path) as TextureImporter;
TextureImporterSettings tImportSettings = new TextureImporterSettings();

tImport.isReadable = true;
//Throws an error NullReferenceException: Object reference not set to an instance of an object
tImport.textureType = TextureImporterType.Sprite;
tImportSettings.spriteMode = 1;
tImport.SetTextureSettings(tImportSettings);

renderer.sprite = //How can I convert the oranges.png texture into a sprite with TextureImporter tImport? I'm stuck on this part.
renderer.material = defaultMaterial;
}

Solved my problem, here is the solution. Note you can swap the path for a URL if you want to load an image from the web.

using UnityEngine;
using UnityEditor;
 
public Material defaultMaterial; //prefab material set already
IEnumerator Start()
	{
		string path = "file://C:\\Users\\i5\\Documents\\My2DProject\\Assets\\oranges.png";
		WWW www = new WWW(path);
		yield return www; 

		SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
		Sprite sprite = new Sprite();
		sprite = Sprite.Create(www.texture, new Rect(0, 0, 170, 170),new Vector2(0, 0),100.0f);

		renderer.sprite = sprite;
		renderer.material = mat;
}

For more see Unity - Scripting API: Sprite.Create