Checking file exists in document library or not using code

By Jatin Prajapati

In this FAQ we will see how to check that a particular file exists in a specific document library or not.

Many of use are trying to upload files to the SharePoint document library programmatically. The following code shows you how to check that a file exists in a particular SharePoint Document library or not.

using System;
using Microsoft.SharePoint;

namespace Jatin
{
    public class Program
    {
         public static void Main(string[] args)
        {
             using (SPSite site = new SPSite("http://localhost:20918"))
            {
                 using (SPWeb web = site.OpenWeb())
                 {
                      string fileName = "myFile.docx";
                     string documentLibName = "My documents";
                     string fileUrl = string.Format("{0}/{1}/{2}", web.Url, documentLibName, fileName);
                    SPFile file = web.GetFile(fileUrl);
                     if (file.Exists)
                       Console.WriteLine("File {0} exists in the site!!!", file.Name);
                     else
                       Console.WriteLine("File not found!!!");
                 }
             }
        }
    }
}

Checking file exists in document library or not using code  (2132 Views)