0

I am attempting to programatically update or create a MS Word or Excel file on a shared drive if the ContentLength does not match. The file is originally stored in a Sharepoint Database. I am able to do this successfully when the file is written to a local directory, however, when this is done to a file on a network drive, even though the file is rewritten, the content becomes corrupted and is unable to be opened properly.

I'm not sure if the issue lies in the WriteFile() and there is a better way to create or update an Excel/Word file using something other than File.Write and file.OpenWrite

My code is as follows:

public void UpsertSharepointFiles()
        {
            try
            {



  var spList = GetSharepointDirectories();

            var targetDir = @"\\111.111.0.11\c$\websites\XXX\FormLibrary";

            IntPtr token = IntPtr.Zero;
            bool valid = LogonUser("administrator",
                        "XXX",
                        "XXX",
                        (int)LogonType.NewCredentials,
                        (int)LogonProvider.WinNT50,
                        ref token);

            if (valid)
            {

                using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(token))
                {

                    CloseHandle(token);

                    //var targetDir = Server.MapPath("~/TempCopy");
                    //var targetDir = @"\\\\222.222.2.22\c$\websites\XXX\FormLibrary";
                    var targetDirInfo = new DirectoryInfo(targetDir);

                    var dirs = targetDirInfo.GetDirectories("*.*", SearchOption.AllDirectories);

                    if (spList != null)
                    {

                        foreach (var spFile in spList)
                        {
                            if (spFile.Content != null)
                            {
                                foreach (var dir in dirs)
                                {
                                    var searchFile = dir.GetFiles(spFile.LeafName);
                                    var currDirName = dir.Name;

                                    if (currDirName == "ABBH")
                                    {
                                        currDirName = "ABB";
                                    }

                                    if (searchFile.Count() == 0) //Web Server - No, SP - Yes
                                    {
                                        CreateFileOnWebServer(currDirName, spFile, targetDir);
                                    }
                                    else // Web Server - Yes, SP - Yes
                                    {
                                        UpdateFileOnWebServer(searchFile, spFile, targetDir, currDirName);
                                    }
                                }

                            }
                        }

                        foreach (var dir in dirs)
                        {
                            DeleteFilesOnWebServerNotInSharepointDb(dir, spList);
                        }
                    }
                }

                lblSuccessMessage.Text = "Forms Library in Website successfully synced with Sharepoint Forms Library!";
                lblSuccessMessage.Visible = true;
            }
        }
        catch (Exception)
        {
            lblErrorMessage.Text = "Error occurred when syncing Forms Library in Website.  Please try again.";
            lblErrorMessage.Visible = true;
        }

    }

private static void DeleteFilesOnWebServerNotInSharepointDb(DirectoryInfo dir, List<SharepointVO> spList)
        {
            var dirFileList = dir.GetFiles();

            var filesOnServerNotInSharepointDb = dirFileList.Where(w => spList.All(s => s.LeafName != w.Name));
            foreach (var file in filesOnServerNotInSharepointDb)
            {
                var fInfo = new FileInfo(file.DirectoryName + @"\" + file.Name).ToString();
                System.IO.File.Delete(fInfo);
            }
        }

        private static void UpdateFileOnWebServer(FileInfo[] searchFile, SharepointVO spFile, string targetDir,
            string currDirName)
        {
            if (searchFile[0].Directory.Name == spFile.Directory)
            {
                // Replace file with Sharepoint file
                if (spFile.ContentLength != searchFile[0].Length) //Checks only first file
                {
                    WriteFile(currDirName, spFile, targetDir);
                }
            }
        }

        private static void CreateFileOnWebServer(string currDirName, SharepointVO spFile, string targetDir)
        {
            if (currDirName == spFile.Directory)
            {
                // Check if directory exists on server
                if (Directory.Exists(targetDir + "/" + currDirName))
                {
                    {
                        {
                            WriteFile(currDirName, spFile, targetDir);
                        }
                    }
                }
                else
                {
                    Directory.CreateDirectory(targetDir + "/" + currDirName);

                    WriteFile(currDirName, spFile, targetDir);
                }
            }
        }

        private static void WriteFile(string currDirName, SharepointVO spFile, string targetDir)
        {
            using (
                Stream fs =
                    System.IO.File.OpenWrite(targetDir + "/" + currDirName + "/" + spFile.LeafName))
            {
                fs.Write(spFile.Content, 0, spFile.Content.Length);
            }
        }

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr token);

        enum LogonType
        {
            Interactive = 2,
            Network = 3,
            Batch = 4,
            Service = 5,
            Unlock = 7,
            NetworkClearText = 8,
            NewCredentials = 9
        }

        enum LogonProvider
        {
            Default = 0,
            WinNT35 = 1,
            WinNT40 = 2,
            WinNT50 = 3
        }
MTL323
  • 177
  • 3
  • 14
  • Any suggestions will be appreciated. – MTL323 Jan 05 '16 at 20:00
  • I suggest looking into EPPlus library for working with Excel found here: http://epplus.codeplex.com – dub stylee Jan 05 '16 at 20:20
  • The problem is that Office files are not just simple text files, so you can't just write plain text to them without corrupting them. – dub stylee Jan 05 '16 at 20:21
  • @dubstyle Does EPPlus work with Word as well? If so, do you have any feedback comparint EPPlus vs. Interop libraries? – MTL323 Jan 05 '16 at 20:23
  • Also, why would I be able to write the file successfully to a local directory? – MTL323 Jan 05 '16 at 20:26
  • I don't think EPPlus works with Word documents. I have only used it with Excel spreadsheets. The way you are opening the files, you could open anything (even an .exe) and append some text to it and save it, but that doesn't mean that it would work properly afterward. – dub stylee Jan 05 '16 at 23:04

0 Answers0