How to Create a SharePoint Folder Through C# Code and Check Whether a Folder Already Exists and upload document Graph API

            var teneantId = ConfigurationManager.AppSettings["TenantId"];

            var clientId = ConfigurationManager.AppSettings["ClientId"];

            var clientSecret = ConfigurationManager.AppSettings["ClientSecret"];




string accessToken = remoteAssessmentDS.GetGraphToken(teneantId, clientId, clientSecret);

string siteId = remoteAssessmentDS.GetSiteId(accessToken, siteName, sitePath);

string driveId = remoteAssessmentDS.GetDriveId(accessToken, siteId, ListTitle);

var folderId = remoteAssessmentDS.EnsureFolder(accessToken, driveId, RelativeUrl);


var filenames = remoteAssessmentDS.GetFilesNamesInFolder_UsingGraph(accessToken, siteId, driveId, folderId);

 var file = Convert.FromBase64String(request.File);

 bool isDocUploaded = remoteAssessmentDS.UploadDocument(accessToken, siteId, driveId, RelativeUrl, request.FileName, file);


 List<string> filenames = new List<string>();

 if (isDocUploaded)

 {

     filenames = remoteAssessmentDS.GetFilesNamesInFolder_UsingGraph(accessToken, siteId, driveId, folderId);

 }












      public static string GetGraphToken(string tenantId, string clientId, string clientSecret)

      {

          System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


          using (var client = new HttpClient())

          {

              var body = new FormUrlEncodedContent(new[]

              {

    new KeyValuePair<string, string>("client_id", clientId),

    new KeyValuePair<string, string>("scope", "https://graph.microsoft.com/.default"),

    new KeyValuePair<string, string>("client_secret", clientSecret),

    new KeyValuePair<string, string>("grant_type", "client_credentials")

});


              var response = client.PostAsync(

                  $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token",

                   body

              ).Result;


              var json = response.Content.ReadAsStringAsync().Result;


              return JObject.Parse(json)["access_token"].ToString();

          }

      }



 public static string GetSiteId(string accessToken, string siteName, string sitePath)

 {

     // STEP 1: Get site ID

     var siteId = GraphGet(

         $"https://graph.microsoft.com/v1.0/sites/{siteName}:{sitePath}",

         accessToken

     )["id"].ToString();


     return siteId;

 }

 private static JObject GraphGet(string url, string token)

 {

     using (var client = new HttpClient())

     {

         client.DefaultRequestHeaders.Authorization =

             new AuthenticationHeaderValue("Bearer", token);


         var response = client.GetAsync(url).Result;

         var json = response.Content.ReadAsStringAsync().Result;


         return JObject.Parse(json);

     }

 }

 public static string GetDriveId(string accessToken, string siteId, string driveName)

 {

     // Get drive (Document Library)

     var drive = GraphGet(

         $"https://graph.microsoft.com/v1.0/sites/{siteId}/drives",

         accessToken

     )["value"]

       .FirstOrDefault(d => d["name"].ToString() == driveName);


     if (drive == null)

         throw new Exception("Drive not found: " + driveName);


     return drive["id"].ToString();

 }



public string EnsureFolder(string accessToken, string driveId, string folderPath)

{

    var parts = folderPath.Split('/');


    JObject current = null;

    string parentId = "root";


    foreach (var part in parts)

    {

        // Check if folder exists

        var children = GraphGet(

            $"https://graph.microsoft.com/v1.0/drives/{driveId}/items/{parentId}/children?$filter=folder ne null",

            accessToken

        )["value"];


        current = children

            .FirstOrDefault(x => x["name"].ToString() == part) as JObject;


        if (current == null)

        {

            // create folder

            var createPayload = new JObject

            {

                ["name"] = part,

                ["folder"] = new JObject(),

                ["@microsoft.graph.conflictBehavior"] = "replace"

            };


            using (var client = new HttpClient())

            {

                client.DefaultRequestHeaders.Authorization =

                    new AuthenticationHeaderValue("Bearer", accessToken);


                var content = new StringContent(createPayload.ToString(), Encoding.UTF8, "application/json");


                var createRes = client.PostAsync(

                    $"https://graph.microsoft.com/v1.0/drives/{driveId}/items/{parentId}/children",

                    content

                ).Result;


                var createJson = createRes.Content.ReadAsStringAsync().Result;

                current = JObject.Parse(createJson);

            }

        }


        parentId = current["id"].ToString();

    }


    return current["id"].ToString();

}


        }



    public List<string> GetFilesNamesInFolder_UsingGraph(string accessToken, string siteId, string driveId, string folderId)

    {

        // List files inside folder

        var items = GraphGet(

            $"https://graph.microsoft.com/v1.0/drives/{driveId}/items/{folderId}/children",

            accessToken

        )["value"];


        var names = new List<string>();


        foreach (var f in items)

        {

            if (f["file"] != null)  // only files

                names.Add(f["name"].ToString());

        }


        return names;

    }

        public bool UploadDocument(string accessToken, string siteId, string driveId, string folderPath, string fileName, byte[] fileBytes)
        {
            string encodedPath = string.IsNullOrEmpty(folderPath) ? fileName : $"{folderPath}/{fileName}";
            string uploadUrl = $"https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/root:/{encodedPath}:/content";

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            using (var content = new ByteArrayContent(fileBytes))
            {
                //content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

                var response = client.PutAsync(uploadUrl, content).Result;

                var createJson = response.Content.ReadAsStringAsync().Result;
                JObject current = JObject.Parse(createJson);

                return true;
            }
        }

Comments

Popular posts from this blog

Power Automate compose vs variable

Update record when checkbox checked using JavaScript and save d365

Power pages custom button add in gried