How to check file exist or not in MVC razor view?

Hi Expert,

I want to check file existence in 'if' condition of my application razor view.

Here is my code,

<span class="qa-q-item-avatar">

                            <a href="@Url.Action("user", "account", new { user = @item.UserName.Replace(" ", "-"), @id = item.UserID })" class="qa-avatar-link">
  if(fileExist){//here we want to check file existence
  <img src="https://www.mindstick.com//Content/img/User Image/@(item.UserID).png" width="30" height="30" class="qa-avatar-image">
  }
  else
  {
  other wise show default image
  }
        </a>
</span>

Please give me the solution to accomplish my task.

Last updated:12/26/2017 2:49:18 AM

1 Answers

Harsh kumar srivastava
Harsh kumar srivastava

Hi, Aarav

I analyzed your code,

Please follow the line of code to achieve your task.

<span class='qa-q-item-avatar'>

                           <a href='@Url.Action('user', 'account', new { user = @item.UserName.Replace(' ', '-'), @id = item.UserID })' class='qa-avatar-link'>
                                @if (File.Exists(@'FilePath'))
                                {
                                    <img src='https://www.mindstick.com//Content/img/User Image/@(item.UserID).png' width='30' height='30' class='qa-avatar-image'>
                                }
                                else
                                {
                                    Default Image Path
                                }
                           </a>
                       </span>

I hope it's informative for you... 


Answer