Search code examples
c#razor

Avoiding an object reference not set to an object


i have a webpage i have been working on, where are forms for adding posts located. The form has a filepicker for images Problem is that when i click the button without an image selected, it gives me an error. I have tried to dodge the error with Try{} Catch{}and with classic if statements.

var formFile = fileUpload.FormFile;
var filePath = Path.Combine(fullPath, formFile.FileName);
var stream = System.IO.File.Create(filePath);

db.VytvoritPrispevekOnas(nazevPrispevku, textPrispevku,"/OnasImages/",formFile.FileName.ToString());

formFile.CopyTo(stream);

stream.Close();

the error comes from the "var filepath" where it doesnt have any object saved in "formFile" to get the "formFile.FileName. The thing is that the "var formFile" is not null, or an empty string or anything Is there a chance to avoid that?

Thank you in advance!


Solution

  • If it doesn't work when not selecting any file, try changing
    var formFile = fileUpload.FormFile;

    To:

    var formFile = fileUpload.FormFile;
    if (formFile is null) return;
    
    ... rest of code