Pomster
Pomster

Reputation: 15197

Why can't I use System.IO.File methods in an MVC controller?

I am trying to see if a file exists before using it in an MVC controller:

string path = "content/image.jpg";

if (File.Exists(path))
{ 
    //Other code
}

The File keyword is underlined in red, and the compiler shows an error:

System.Web.MVC.Controller.File(string, string, string) is a 'method', witch is not valid in the given context.

How can I use File.Exists() in a controller?

Upvotes: 53

Views: 21129

Answers (2)

Ivan  Silkin
Ivan Silkin

Reputation: 485

In .Net 7 there was an error CS0234 after updating from .net 6 or renaming the controller namespace, which states in YourSolutionNamespace.YourControllerName there is no type or namespace IO , which can be solved with a global::

/*var stream = */ global::System.IO.File.OpenRead(filePath);

directive.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

You should prefix it with a namespace:

if (System.IO.File.Exists(picPath))
{ 
    //Other code
}

The reason for that is because you are writing this code inside a controller action which already defines a File method on the Controller class.

Upvotes: 101

Related Questions