0

I am uploading a file to a SharePoint Online document library from a byte array and on execution I am getting the error "File Not found"

public static bool UploadFile(SP sp, string folderName, string fileNameWithExtension, byte[] fileContent, TraceWriter log)
{
    bool result = false;
    try
    {       
        SecureString securePwd = new SecureString();
        char[] pwdarray = sp.pwd.ToCharArray();

        foreach (var item in pwdarray)
        {
            securePwd.AppendChar(item);
        }

        SharePointOnlineCredentials creds = new SharePointOnlineCredentials(sp.id, securePwd);

        using (ClientContext clientContext = new ClientContext(sp.url))
        {
            log.Info("UploadToSharePoint 1");

            clientContext.Credentials = creds;
            clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
            Web web = clientContext.Web;           

            var fileCreationInformation = new FileCreationInformation();
            fileCreationInformation.Content = fileContent;
            fileCreationInformation.Overwrite = true;          

            fileCreationInformation.Url = fileNameWithExtension;            
            Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle("All Attachments");
            docs.RootFolder.Folders.Add(folderName);
            Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(fileCreationInformation);           
            clientContext.ExecuteQuery();          
            return result = true;    
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

How can I resolve the issue?

0

Try the following code, which works fine in my environment:

static void UploadFiles(string siteUrl, string userName, string password, string targetLibrary, string filePath)
        {
            using (ClientContext context = new ClientContext(siteUrl))
            {
                Console.WriteLine("1. Connecting to SharePoint Online....");

                bool isOffice365 = false;
                Boolean.TryParse(ConfigurationManager.AppSettings["IsOffice365"], out isOffice365);
                if (isOffice365)
                {
                    SecureString securePassword = new SecureString();
                    foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);

                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(userName, securePassword);
                    context.Credentials = onlineCredentials;
                }
                else
                {

                }

                List list = context.Web.Lists.GetByTitle(targetLibrary);
                context.Load(list.RootFolder);
                context.ExecuteQuery();

                Console.WriteLine("2. Reading all folders from FileSystem...");
                string[] allDirectories = GetFolders(filePath);
                Console.WriteLine("\tFound {0} folders...", allDirectories.Count());

                Console.WriteLine("3. Looping each folder...");
                int folderCount = 0;

                #region -- Folders --
                foreach (string folderPath in allDirectories)
                {
                    folderCount++;
                    DirectoryInfo di = new DirectoryInfo(folderPath);
                    string fileSystemRelativePath = folderPath.Replace(filePath, "");
                    Console.WriteLine("\t{0}. Processing {1} folder...", folderCount, fileSystemRelativePath);

                    string folderRelativeUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fileSystemRelativePath.Replace('\\', '/'));
                    Console.WriteLine("\t\t1. Verifying the path \"{0}\" in SharePoint..", folderRelativeUrl);
                    Folder spoFolder = GetFolderByRelativeUrl(context.Web, folderRelativeUrl);

                    Console.WriteLine("\t\t2. Creating folder \"{0}\" in SharePoint if not exists...", folderRelativeUrl);
                    if (spoFolder == null)
                    {
                        spoFolder = CreateFolder(context.Web, list, folderRelativeUrl, di.Name);
                    }

                    if (spoFolder != null)
                    {
                        Console.WriteLine("\t\t3. Reading files from Folder {0}...", fileSystemRelativePath);
                        string[] sourceFiles = Directory.GetFiles(folderPath);
                        Console.WriteLine("\t\t\tFound {0} files...", sourceFiles.Count());

                        Console.WriteLine("\t\t4. Uploading files to SharePoiont...");
                        int fileCount = 0;

                        foreach (string sourceFile in sourceFiles)
                        {
                            fileCount++;
                            string fileName = Path.GetFileName(sourceFile);
                            string fileUrl = string.Format("{0}/{1}", spoFolder.ServerRelativeUrl, fileName);
                            Console.WriteLine("\t\t\t{0}. Processing {1}...", fileCount, fileUrl);
                            using (FileStream fs = new FileStream(sourceFile, FileMode.Open))
                            {
                                Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
                            }
                        }
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("\t\t\tFolder creating failed or could not found the folder...");
                        Console.ResetColor();
                    }
                } 
                #endregion
                Console.WriteLine("4. Processing files in root folder");
                Console.WriteLine("\t\t1. Reading files from Folder {0}...", filePath);
                string[] rootFiles = Directory.GetFiles(filePath);
                Console.WriteLine("\t\t\tFound {0} files...", rootFiles.Count());

                Console.WriteLine("\t\t1. Uploading files to SharePoiont...");

                int rootfilesCount = 0;
                foreach (string rootFilePath in rootFiles)
                {
                    rootfilesCount++;
                    string fileName = Path.GetFileName(rootFilePath);
                    string fileUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fileName);
                    Console.WriteLine("\t\t\t{0}. Processing {1}...", rootfilesCount, fileUrl);
                    using (FileStream fs = new FileStream(rootFilePath, FileMode.Open))
                    {
                        Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
                    }
                }
            }
        }

The source code is here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.