0

I have a code like this:

string fileLocation = Request.Form["FileName"].ToString(); 

if (!string.IsNullOrEmpty(fileLocation))
{                          
    var deleteFile = fileLocation.Split('\\')[1];
    var pathe = Path.Combine(uploadPath, deleteFile;
    if (System.IO.File.Exists(pathFile))
    {
        System.IO.File.Delete(pathFile);
    }
}

Usually if i don't select a file, Request.Form["FileName"].ToString() will return a SystemNullException which I intend to set it as null.

Is there anyway i can do it without using try catch?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Huang Lee
  • 57
  • 9
  • 5
    something like `string fileLocation = Request?.Form["FileName"]?.ToString();` – Dmitry Bychenko Jul 03 '18 at 09:35
  • 1
    Some part of `Request.Form["FileName"].ToString()` will be null. Find out which bit by adding a breakpoint and generating the condition, then put in a specific check, e.g., `if (Request != null)`, or `if (Request.Form["FileName"] != null)` before the `.ToString()` call. – Ian Jul 03 '18 at 09:39

2 Answers2

3

If Request.Form["FileName"] returns null then you can't do .ToString().

So you can use null propagator to get around this:

Request.Form["FileName"]?.ToString()
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ross Miller
  • 656
  • 3
  • 9
1

Just check before applying .ToString.

var result = Request.Form["FileName"];
if(result != null)
{
    string fileLocation = result.ToString();
    if (!string.IsNullOrEmpty(fileLocation))
    {
        var deleteFile = fileLocation.Split('\\')[1];
        var pathe = Path.Combine(uploadPath, deleteFile;
        if (System.IO.File.Exists(pathFile))
        {
            System.IO.File.Delete(pathFile);
        }
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85