internal SPOFile AddTemplateFile(string leafName, TemplateFileType templateType, bool throwIfExists)
        {
            if (string.IsNullOrEmpty(leafName))
            {
                throw new ArgumentNullException("The leafName name cannot be null.");
            }
            if (!leafName.ToLower().EndsWith(".aspx"))
            {
                leafName += ".aspx";
            }

            SPOFile existingFile = null;

            try
            {
                existingFile = GetFile(leafName);
            }
            catch { }
            if (existingFile != null && existingFile.Exists)
            {
                if (throwIfExists)
                {
                    throw new FileExistsException("The specified file already exists.");
                }

                return(existingFile);
            }

            string url  = ServerRelativeUrl.TrimEnd('/') + "/" + leafName;
            var    file = _folder.Files.AddTemplateFile(url, templateType);

            SPOFile.LoadFile(SPOSiteContext.CurrentSiteContext.Context, file);
            return(new SPOFile(file));
        }
        public void SaveFileLocallyViaREST(string directory, bool overwrite)
        {
            string path = System.IO.Path.Combine(directory, Name);

            if (System.IO.File.Exists(path))
            {
                if (!overwrite)
                {
                    throw new Exception("The file already exists locally.");
                }
                System.IO.File.Delete(path);
            }
            string folderUrl = ServerRelativeUrl.Substring(0, ServerRelativeUrl.Length - Name.Length - 1);
            string restCmd   = string.Format("/_api/web/GetFolderByServerRelativeUrl('{0}')/files('{1}')/$value", folderUrl, Name);

            Uri uri = new Uri(_file.Context.Url.TrimEnd('/') + restCmd);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Credentials = SPOSiteContext.CurrentSiteContext.Context.Credentials;
            request.Method      = WebRequestMethods.Http.Get;
            request.Headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.ContentLength > 0)
            {
                response.ContentLength = response.ContentLength;
            }
            using (System.IO.Stream s = response.GetResponseStream())
                using (System.IO.FileStream fs = System.IO.File.Create(path))
                {
                    s.CopyTo(fs);
                }
        }