client object model – CSOM does not use windows credential and giving “The remote server returned an error: (403) Forbidden.” error


I have a console application with .NET Framework which uploads a file using CSOM. When I run the application I get below error:

The remote server returned an error: (403) Forbidden.

However, When I pass my windows credential it works fine. I don’t want to hardcode my credential in code due to security purpose. Is there any work around except passing credential in the code?

My code is as below:

using System;
using System.IO;
using System.Linq;
using System.Security;
using Microsoft.SharePoint.Client;
using ClientOM = Microsoft.SharePoint.Client;


namespace ConsoleApp3
{

class Program
{
    static void Main(string() args)
    {

        ClientContext clientContext = new ClientContext("https://companyname.sharepoint.com");

        //SecureString passWord = new SecureString();
        //foreach (char c in "HelloWorld@1234".ToCharArray()) passWord.AppendChar(c);
        //clientContext.Credentials = new SharePointOnlineCredentials("jay.desai@company.com", passWord);
        clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

        using(FileStream fileStream = new FileStream(@"C:Usersjay.desaiDesktopLSRSQL01_ACXM_20201003.html", FileMode.Open))
            ClientOM.File.SaveBinaryDirect(clientContext, "/sites/DataServices/Shared Documents/Data Dictionaries/LSRSQL01_ACXM_20201003.html", fileStream, true);
    }
}

}