Beispiel #1
0
        //void LoadFileSystems()
        //{
        //    string safeFullName = @"\\?\" + FullName;
        //    List<string> results = new List<string>();
        //    WIN32_FIND_DATA findData;
        //    IntPtr findHandle = LongPath.Directory.FindFirstFile(safeFullName + @"\*", out findData);

        //    string newFullName="";
        //    string currentFileName = "";

        //    if (findHandle != INVALID_HANDLE_VALUE)
        //    {
        //        bool found;

        //        do
        //        {
        //            currentFileName = findData.cFileName;
        //            newFullName = Path.Combine(FullName, currentFileName);

        //            // if this is a directory, find its contents
        //            if (((int)findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
        //            {
        //                if (currentFileName != "." && currentFileName != "..")
        //                {
        //                    Directories.Add(newFullName);
        //                }
        //            }
        //            else // This is a file
        //            {
        //                Files.Add(new FileDataInfo
        //                {
        //                    FullName = newFullName,
        //                    DestinyDirectoryPath = DestinyPath,
        //                    Name = Path.GetFileName(newFullName),
        //                    DestinyPath = Path.Combine(DestinyPath, Path.GetFileName(newFullName)),
        //                    Size = findData.Length,
        //                    //FileAttributes = findData.dwFileAttributes,
        //                    //CreationTime=findData.ftCreationTime,
        //                    //LastAccessTime=findData.ftLastAccessTime,
        //                    //LastWriteTime=findData.ftLastWriteTime
        //                });
        //            }

        //            // find next
        //            found = LongPath.Directory.FindNextFile(findHandle, out findData);
        //        }
        //        while (found);
        //    }

        //    // close the find handle
        //    LongPath.File.FindClose(findHandle);

        //    FileSystemsLoaded = true;
        //}

        public List <FileDataInfo> GetFiles()
        {
            //if (!FileSystemsLoaded)
            //    LoadFileSystems();

            var dinfo = new Delimon.Win32.IO.DirectoryInfo(FullName);

            //var newFullName = Delimon.Win32.IO.Path.Combine(FullName, f.Name);
            Files = dinfo.GetFiles().Select(f => new FileDataInfo()
            {
                FullName             = Delimon.Win32.IO.Path.Combine(FullName, f.Name),
                DestinyDirectoryPath = DestinyPath,
                Name           = Path.GetFileName(f.Name),
                DestinyPath    = Path.Combine(DestinyPath, Path.GetFileName(Delimon.Win32.IO.Path.Combine(FullName, f.Name))),
                Size           = f.Length,
                FileAttributes = f.Attributes,
                CreationTime   = f.CreationTime,
                LastAccessTime = f.LastAccessTime,
                LastWriteTime  = f.LastWriteTime
            }).ToList();

            Files.Sort(Compare);

            return(Files);
        }
Beispiel #2
0
        /// <summary>
        /// delete folder
        /// </summary>
        /// <param name="sdei">sync execution information about directory</param>
        /// <param name="interruptChecker">is called when the cancellation or pause request should be checked in order to handel them</param>
        /// <returns>true if the operation was canceled</returns>
        public static bool DeleteFolder(SyncDirExecutionInfo sdei, Func <bool> interruptChecker)
        {
            if (interruptChecker())
            {
                return(true);
            }

            string ddp = sdei.AbsoluteDestPath;

            Delimon.Win32.IO.DirectoryInfo ddi = new Delimon.Win32.IO.DirectoryInfo(ddp);

            if (!ddi.Exists)
            {
                return(false);
            }

            //do not remove if directory is not empty
            if (ddi.GetFiles().Length > 0 || ddi.GetDirectories().Length > 0)
            {
                sdei.SyncDirInfo.Conflicted(new DirConflictInfo(sdei.SyncDirInfo, ConflictType.DirNotEmpty,
                                                                sdei.Direction == SyncDirection.To1 ? 1 : 2, "RunFolderDeletionTask",
                                                                $"The directory to be deleted was not empty. Path: {sdei.SyncDirInfo.DirInfo.FullPath}", null));
                return(false);
            }

            interruptChecker();

            sdei.StartedNow();
            try
            {
                ddi.Delete();
                sdei.SyncDirInfo.SyncStatus = SyncElementStatus.ChangeApplied;
            }
            catch (Exception e)
            {
                sdei.SyncDirInfo.Conflicted(new DirConflictInfo(sdei.SyncDirInfo, ConflictType.Unknown,
                                                                sdei.Direction == SyncDirection.To2 ? 2 : 1, "RunFolderDeletionTask", e.Message, e));
            }
            sdei.EndedNow();

            return(false);
        }
Beispiel #3
0
        /// <summary>
        /// delete folder
        /// </summary>
        /// <param name="sdei">sync execution information about directory</param>
        /// <param name="interruptChecker">is called when the cancellation or pause request should be checked in order to handel them</param>
        /// <returns>true if the operation was canceled</returns>
        public static bool DeleteFolder(SyncDirExecutionInfo sdei, Func<bool> interruptChecker)
        {
            if (interruptChecker()) return true;

            string ddp = sdei.AbsoluteDestPath;
            Delimon.Win32.IO.DirectoryInfo ddi = new Delimon.Win32.IO.DirectoryInfo(ddp);

            if (!ddi.Exists)
                return false;

            //do not remove if directory is not empty
            if (ddi.GetFiles().Length > 0 || ddi.GetDirectories().Length > 0)
            {
                sdei.SyncDirInfo.Conflicted(new DirConflictInfo(sdei.SyncDirInfo, ConflictType.DirNotEmpty,
                    sdei.Direction == SyncDirection.To1 ? 1 : 2, "RunFolderDeletionTask",
                    $"The directory to be deleted was not empty. Path: {sdei.SyncDirInfo.DirInfo.FullPath}", null));
                return false;
            }

            interruptChecker();

            sdei.StartedNow();
            try
            {
                ddi.Delete();
                sdei.SyncDirInfo.SyncStatus = SyncElementStatus.ChangeApplied;
            }
            catch (Exception e)
            {
                sdei.SyncDirInfo.Conflicted(new DirConflictInfo(sdei.SyncDirInfo, ConflictType.Unknown,
                    sdei.Direction == SyncDirection.To2 ? 2 : 1, "RunFolderDeletionTask", e.Message, e));
            }
            sdei.EndedNow();

            return false;
        }
Beispiel #4
0
        //private String DecodeStream(string s) {
        //	Encoding defEnc = Encoding.Default;
        //	Encoding isoEnc = Encoding.GetEncoding(850);
        //	byte[] defBytes = defEnc.GetBytes(s);
        //	byte[] isoBytes = Encoding.Convert(defEnc, isoEnc, defBytes);
        //	name = isoEnc.GetString(isoBytes);

        //	return name;
        //}

        private void CreateList(string sDir)
        {
            try {
                folder = new Delimon.Win32.IO.DirectoryInfo(sDir);

                foreach (Delimon.Win32.IO.FileInfo f in folder.GetFiles())
                {
                    lista.Add($"{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}");
                    //await FileWriteAsync($"{Environment.NewLine}{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}");
                    //using (System.IO.StreamWriter w = Delimon.Win32.IO.File.AppendText($"{baseDir}lista_arquivos.txt")) {
                    //    w.Write($"{Environment.NewLine}{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}");
                    //    w.Close();
                    //    w.Dispose();
                    //}
                    //sb.Append($"{Environment.NewLine}{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}");
                    if (lista.Count >= 100000)
                    {
                        System.IO.File.AppendAllLines($"{baseDir}lista_arquivos.txt", lista);
                        //List<List<String>> l = new List<List<String>>();
                        //l.Add(lista.ToList());
                        lista.Clear();
                        lista.TrimExcess();
                    }

                    progressBar.Dispatcher.Invoke(() => progressBar.Value++, DispatcherPriority.Background);

                    if (f.Extension.Equals(".pdf", StringComparison.OrdinalIgnoreCase))
                    {
                        using (var stream = Delimon.Win32.IO.File.OpenRead(f.FullName)) {
                            using (var ms = new System.IO.MemoryStream()) {
                                stream.CopyTo(ms);
                                ms.Position = 0;
                                CountPdfPages(ms);
                            }
                        }
                    }

                    if (f.Extension.Equals(".doc", StringComparison.OrdinalIgnoreCase) || f.Extension.Equals(".docx", StringComparison.OrdinalIgnoreCase))
                    {
                        using (var stream = Delimon.Win32.IO.File.OpenRead(f.FullName)) {
                            using (var ms = new System.IO.MemoryStream()) {
                                stream.CopyTo(ms);
                                ms.Position = 0;
                                CountWordPages(ms);
                            }
                        }
                    }

                    if (f.Extension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
                    {
                        //using (var fs = new System.IO.StreamReader(Delimon.Win32.IO.File.OpenRead(f.FullName), Encoding.GetEncoding(850))) {
                        //using(ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Read, Encoding.GetEncoding(850))) {

                        //ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);
                        //System.IO.Stream zipStream = zipFile.GetInputStream(fs);
                        fs = Delimon.Win32.IO.File.OpenRead(f.FullName);

                        using (var archive = new ZipArchive(fs, ZipArchiveMode.Read, false, Encoding.GetEncoding(850))) {
                            foreach (ZipArchiveEntry entry in archive.Entries)
                            {
                                if (entry.Name != "")
                                {
                                    if (entry.Name.Contains("."))
                                    {
                                        ext = entry.Name.Substring(entry.Name.LastIndexOf(".")).ToLower();
                                    }
                                    else
                                    {
                                        ext = "null";
                                    }
                                    rep = new StringBuilder(@"\");

                                    if (entry.FullName.Contains("/"))
                                    {
                                        rep.Append(entry.FullName.Substring(0, entry.FullName.LastIndexOf("/")));
                                        rep.Replace("/", @"\");
                                    }
                                    else
                                    {
                                        rep.Clear();
                                    }

                                    lista.Add($"{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}");
                                    //await FileWriteAsync($"{Environment.NewLine}{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}");
                                    //using (System.IO.StreamWriter w = Delimon.Win32.IO.File.AppendText($"{baseDir}lista_arquivos.txt")) {
                                    //    w.Write($"{Environment.NewLine}{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}");
                                    //    w.Close();
                                    //    w.Dispose();
                                    //}
                                    //sb.Append($"{Environment.NewLine}{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}");

                                    if (lista.Count >= 100000)
                                    {
                                        System.IO.File.AppendAllLines($"{baseDir}lista_arquivos.txt", lista);
                                        lista.Clear();
                                        lista.TrimExcess();
                                    }

                                    if (ext.Equals(".pdf", StringComparison.OrdinalIgnoreCase))
                                    {
                                        using (var stream = entry.Open()) {
                                            using (var ms = new System.IO.MemoryStream()) {
                                                stream.CopyTo(ms);
                                                ms.Position = 0;
                                                CountPdfPages(ms);
                                            }
                                        }
                                    }

                                    if (ext.Equals(".doc", StringComparison.OrdinalIgnoreCase) || ext.Equals(".docx", StringComparison.OrdinalIgnoreCase))
                                    {
                                        using (var stream = entry.Open()) {
                                            using (var ms = new System.IO.MemoryStream()) {
                                                stream.CopyTo(ms);
                                                ms.Position = 0;
                                                CountWordPages(ms);
                                            }
                                        }
                                    }

                                    if (ext.Equals(".zip", StringComparison.OrdinalIgnoreCase))
                                    {
                                        fn = f.FullName;
                                        ZipList(fn, entry);
                                    }
                                }
                            }
                        }
                        //}
                        //}
                    }
                }

                foreach (string d in Delimon.Win32.IO.Directory.GetDirectories(sDir))
                {
                    CreateList(d);
                }
            } catch {
                //System.Windows.Forms.MessageBox.Show($"{exc.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Determines whether the specified folder contains files with
        /// file extensions that do not match the content.
        /// </summary>
        /// <param name="folderPath">The folder path.</param>
        /// <param name="recursive">if set to <c>true</c> [recursive].</param>
        /// <returns>
        ///     <c>true</c> if [contains folder prohibited content]
        /// [the specified folder path]; otherwise, <c>false</c>.
        /// </returns>
        private void containsFolderVerifyContent(
            Delimon.Win32.IO.DirectoryInfo folderPath,
            bool recursive,
            ref List <FileResult> verifiedFiles,
            ref List <FileResult> unVerifiedFiles,
            ref List <FileResult> unknownFiles,
            ref List <FileResult> ProhibitedFiles,
            ref bool blShuttingDown,
            string excludeFolders,
            HeaderSignature[] sigs,
            bool blValidateZipFiles,
            bool blHeaderVerificationIgnoreFileExtensions,
            bool blProhibitedFilesIgnoreFileExtensions
            )
        {
            WriteError(
                string.Format(
                    @"Audit Folder ContentDetectorEngine: Checking folder '{0}'.",
                    folderPath.FullName), System.Diagnostics.EventLogEntryType.Information, 6000, 60, true);



            if (sigs == null)
            {
                sigs = HeaderSignature.StockSignatures;
            }



            Delimon.Win32.IO.FileInfo[] filePaths = folderPath.GetFiles();

            int index = 0;

            //Load either default signatures or custom for determining ExtensionSupported?



            foreach (Delimon.Win32.IO.FileInfo filePath in filePaths)
            {
                if (blShuttingDown)
                {
                    WriteError(
                        string.Format(
                            @"Audit Folder ContentDetectorEngine: Shutting Down: was about to check file '{0}'.",
                            filePath.FullName), System.Diagnostics.EventLogEntryType.Information, 6000, 60, true);
                    break;
                }
                try
                {
                    WriteError(
                        string.Format(
                            @"Audit Folder ContentDetectorEngine: [{0}/{1}] Checking file '{2}' ({3:0,0} bytes).",
                            index + 1, filePaths.Length,
                            filePath.FullName,
                            filePath.Length), System.Diagnostics.EventLogEntryType.Information, 6000, 60, true);

                    bool blVerifiedContent = false;

                    blVerifiedContent = DoVerifyFileHeader(filePath, sigs, blHeaderVerificationIgnoreFileExtensions);

                    //Verify File Headers
                    if (!HeaderSignature.ExtensionSupported(filePath.Extension, sigs))
                    {
                        unknownFiles.Add(new FileResult(filePath));
                    }
                    else if (!blVerifiedContent)
                    {
                        if (blValidateZipFiles && HeaderSignature.ZipRelatedExtension(filePath.Extension))
                        {
                            using (Stream filestream1 = filePath.Open(Delimon.Win32.IO.FileMode.Open, Delimon.Win32.IO.FileAccess.Read, Delimon.Win32.IO.FileShare.ReadWrite))
                            {
                                try
                                {
                                    if (ZipFile.IsZipFile(filestream1, true) == false)
                                    {
                                        unVerifiedFiles.Add(new FileResult(filePath, "Error: Zip File is Corrupted or Encrypted!"));
                                    }
                                    try
                                    {
                                        filestream1.Close();
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                                catch (Exception ex)
                                {
                                    WriteError(
                                        string.Format(
                                            @"Audit Folder ContentDetectorEngine: [{0}/{1}] Error Zip Checking file '{2}' ({3:0,0} bytes). " + ex.Message,
                                            index + 1, filePaths.Length,
                                            filePath.FullName,
                                            filePath.Length), System.Diagnostics.EventLogEntryType.Error, 6000, 60, false);
                                    unknownFiles.Add(new FileResult(filePath, "Error checking the file"));
                                }
                            }
                        }
                        else
                        {
                            unVerifiedFiles.Add(new FileResult(filePath, "Extension and file header for the file does not match any expected file signature."));
                        }
                    }
                    else
                    {
                        if (blValidateZipFiles && blVerifiedContent && HeaderSignature.IsZipRelatedFile(filePath))
                        {
                            if (ZipFile.IsZipFile(filePath.OpenRead(), true) == false)
                            {
                                unVerifiedFiles.Add(new FileResult(filePath, "Error: Zip File is Corrupted or Encrypted!"));
                            }
                            else
                            {
                                verifiedFiles.Add(new FileResult(filePath, "Zip File Verified"));
                            }
                        }
                        else
                        {
                            verifiedFiles.Add(new FileResult(filePath));
                        }
                    }

                    //check for prohibited files
                    if (ContainsProhibitedFileContent(filePath, sigs, blProhibitedFilesIgnoreFileExtensions))
                    {
                        ProhibitedFiles.Add(new FileResult(filePath));
                    }
                }
                catch (Exception)
                {
                    WriteError(
                        string.Format(
                            @"Audit Folder ContentDetectorEngine: [{0}/{1}] Error Checking file '{2}' ({3:0,0} bytes).",
                            index + 1, filePaths.Length,
                            filePath.FullName,
                            filePath.Length), System.Diagnostics.EventLogEntryType.Error, 6000, 60, false);
                    unknownFiles.Add(new FileResult(filePath, "Error checking the file"));
                }


                index++;
            }



            // --

            if (recursive)
            {
                Delimon.Win32.IO.DirectoryInfo[] folderPaths = folderPath.GetDirectories();

                foreach (Delimon.Win32.IO.DirectoryInfo childFolderPath in folderPaths)
                {
                    bool blIgnoreDirectory = false;
                    if (blShuttingDown)
                    {
                        WriteError(
                            string.Format(
                                @"Audit Folder ContentDetectorEngine: Shutting Down: was about to check folder '{0}'.",
                                childFolderPath.FullName), System.Diagnostics.EventLogEntryType.Information, 6000, 60, true);
                        break;
                    }

                    try
                    {
                        char[]   delimiters             = new char[] { ';' };
                        string[] strArr_excludedfolders = excludeFolders.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                        if (!(strArr_excludedfolders == null || strArr_excludedfolders.Length == 0))
                        {
                            //loop through excluded folders
                            foreach (string strExclude in strArr_excludedfolders)
                            {
                                if (childFolderPath.Name.ToLower() == strExclude.ToLower())
                                {
                                    blIgnoreDirectory = true;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }

                    if (!blIgnoreDirectory)
                    {
                        containsFolderVerifyContent(childFolderPath, recursive, ref verifiedFiles, ref unVerifiedFiles, ref unknownFiles, ref ProhibitedFiles, ref blShuttingDown, excludeFolders, sigs, blValidateZipFiles, blHeaderVerificationIgnoreFileExtensions, blProhibitedFilesIgnoreFileExtensions);
                    }
                }
            }
        }