In this post, we discuss, How to check if the file already exists in the Server folder? .I am working on a Mvc Web Application. Where the user has to upload the Transaction Receipt So that our Web Application should get the Receipt from the users for that I need a code to verify whether a Receipt exists or not in the server folder.For achieving that task I have written some lines of code.please have look if you looking for the same.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="CheckFile" OnClick="Button1_Click" style="height: 26px" />
        <br />
        <asp:Image ID="Image1" runat="server" />
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        

    }

    private bool FileExist()
    {
        string spath = System.Web.HttpContext.Current.Server.MapPath("~/upload");
        string path = spath + "/picture.jpg";
        FileInfo imageFile = new FileInfo(path);
        bool fileExists = imageFile.Exists;
        return fileExists;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileExist())
        {
            Image1.ImageUrl = "~/upload/picture.jpg";
        }
        else
        {
            Response.Write("<script>alert('Image not found')</script>");
        }

    }
}

Check if a file exists on the server in  Mvc

 //We need to convert the path to a physical path with Server.MapPath(relativePath)
        if (File.Exists(Server.MapPath("~/upload/picture.jpg")))
        {

        }

File.Exists() method of the File class in the System.IO namespace. Using that method you can easily determine whether a file exists in the folder or not.

File.Exists() is the popular and simplest ways to check verify file existing or not in the folder. this returns true or false in the file depending on file exists or not.

We should not use File.Exists() to validate path, this method checks if the file specified in path exists file. And return an invalid path to Exists returns false.

The post How To Check Whether File Exists or Not in Asp.Net ? appeared first on Software Development | Programming Tutorials.