Inheritance: IFileSystemObject
Exemple #1
3
 /// <summary>
 /// Iterate thru all the filesysteminfo objects and add it to our zip file
 /// </summary>
 /// <param name="fileSystemInfosToZip">a collection of files/directores</param>
 /// <param name="z">our existing ZipFile object</param>
 private static void GetFilesToZip(FileSystemInfo[] fileSystemInfosToZip, ZipFile z)
 {
     //check whether the objects are null
     if (fileSystemInfosToZip != null && z != null)
     {
         //iterate thru all the filesystem info objects
         foreach (FileSystemInfo fi in fileSystemInfosToZip)
         {
             //check if it is a directory
             if (fi is DirectoryInfo)
             {
                 DirectoryInfo di = (DirectoryInfo)fi;
                 //add the directory
                 z.AddDirectory(di.FullName);
                 //drill thru the directory to get all
                 //the files and folders inside it.
                 GetFilesToZip(di.GetFileSystemInfos(), z);
             }
             else
             {
                 //add it
                 z.Add(fi.FullName);
             }
         }
     }
 }
        internal static bool ImportBook(FileSystemInfo file, IMLSection booksSection, string fileName, string ext)
        {

            if (ext != ".pdf" && ext != ".PDF" && ext != ".djvu" && ext != ".DJVU")
                return false;

            if (!Settings.EnableBooksImporter)
                return false;


            bool itemfound = false;
            IMLItemList list = booksSection.SearchByLocation(file.FullName);


            foreach (IMLItem item in list.Where(item => item.Location == file.FullName))
                itemfound = true;


            if (itemfound)
                return true;

            Application.DoEvents();
            Debugger.LogMessageToFile("Importing book " + file.Name + "...");
            Importer.ThisProgress.Progress(Importer.CurrentProgress, "Importing book " + file.Name + "...");
            IMLItem Item;
            Helpers.AddFileToSection(out Item, booksSection, fileName, file.FullName, file.FullName);
            return true;



        }
        private static void CopyDirectory(string sourcePath, string destinationPath)
        {
            //-----------------------------------------------------------------------
            System.IO.DirectoryInfo sourceDirectoryInfo = new System.IO.DirectoryInfo(sourcePath);

            // If the destination folder don't exist then create it
            if (!System.IO.Directory.Exists(destinationPath))
            {
                System.IO.Directory.CreateDirectory(destinationPath);
            }

            System.IO.FileSystemInfo fileSystemInfo = null;
            foreach (FileSystemInfo fileSystemInfo_loopVariable in sourceDirectoryInfo.GetFileSystemInfos())
            {
                fileSystemInfo = fileSystemInfo_loopVariable;
                string destinationFileName = System.IO.Path.Combine(destinationPath, fileSystemInfo.Name);

                // Now check whether its a file or a folder and take action accordingly
                if (fileSystemInfo is System.IO.FileInfo)
                {
                    System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, true); Console.WriteLine(
                        FolderDifference(sourcePath, PluginFolder) + "\\" + fileSystemInfo);
                }
                else
                {
                    // Recursively call the mothod to copy all the neste folders
                    CopyDirectory(fileSystemInfo.FullName, destinationFileName);
                }
            }
        }
Exemple #4
0
        public IDirectoryTreeNode Create(FileSystemInfo root, FileSystemInfo location)
        {
            string relativePathFromRoot = root == null ? @".\" : PathExtensions.MakeRelativePath(root, location);

            var directory = location as DirectoryInfo;
            if (directory != null)
            {
                return new FolderDirectoryTreeNode(directory, relativePathFromRoot);
            }

            var file = location as FileInfo;
            if (relevantFileDetector.IsFeatureFile(file))
            {
                Feature feature = featureParser.Parse(file.FullName);
                if (feature != null)
                {
                    return new FeatureDirectoryTreeNode(file, relativePathFromRoot, feature);
                }

                throw new InvalidOperationException("This feature file could not be read and will be excluded");
            }
            else if (relevantFileDetector.IsMarkdownFile(file))
            {
                XElement markdownContent = htmlMarkdownFormatter.Format(File.ReadAllText(file.FullName));
                return new MarkdownTreeNode(file, relativePathFromRoot, markdownContent);
            }

            throw new InvalidOperationException("Cannot create an IItemNode-derived object for " + file.FullName);
        }
        internal static bool SkipAlreadyImportedFiles
            (FileSystemInfo file, IEnumerable<string> filmLocations, 
             IEnumerable<string> tvshowsLocations, IEnumerable<string> musicLocations)
        {

            //TODO: Make existing item search faster by specifying the media type to be scanned.

            Helpers.UpdateProgress("Importing Media Files...",
                "Searching media library for existing file entry...", null);


            if (SearchForExistingItemInMoviesSection(file, filmLocations))
                return true;

            if (SearchForExistingItemInTvShowsSection(file, tvshowsLocations))
                return true;

            // ReSharper disable ConvertIfStatementToReturnStatement
            if (SearchForExistingItemInMusicSection(file, musicLocations))
            // ReSharper restore ConvertIfStatementToReturnStatement
                return true;




            return false;


        }
 public FeatureDirectoryTreeNode(FileSystemInfo location, string relativePathFromRoot, Feature feature)
 {
     this.OriginalLocation = location;
     this.OriginalLocationUrl = location.ToUri();
     this.RelativePathFromRoot = relativePathFromRoot;
     this.Feature = feature;
 }
        /// <summary>
        /// 编译文件AssetBundle名字
        /// </summary>
        /// <param name="file">文件信息</param>
        /// <param name="basePath">基础路径</param>
        protected static void BuildFileBundleName(FileSystemInfo file , string basePath)
        {
            string extension = file.Extension;
            string fullName = file.FullName.Standard();
            string fileName = file.Name;
            string baseFileName = fileName.Substring(0 , fileName.Length - extension.Length);
            string assetName = fullName.Substring(basePath.Length);
            assetName = assetName.Substring(0 , assetName.Length - fileName.Length).TrimEnd('/');

            if(baseFileName + extension == ".DS_Store"){ return; }

            int variantIndex = baseFileName.LastIndexOf(".");
            string variantName = string.Empty;

            if(variantIndex > 0){

                variantName = baseFileName.Substring(variantIndex + 1);

            }

            AssetImporter assetImporter = AssetImporter.GetAtPath("Assets" + Env.ResourcesBuildPath + assetName + "/" + baseFileName + extension);
            assetImporter.assetBundleName = assetName.TrimStart('/');
            if(variantName != string.Empty){

                assetImporter.assetBundleVariant = variantName;

            }
        }
        private static bool SearchForExistingItemInMoviesSection(FileSystemInfo file, IEnumerable<string> filmLocations,
             IMLSection section)
        {
            if (filmLocations == null)
                return false;

            // ReSharper disable LoopCanBeConvertedToQuery
            foreach (var movieFolder in Settings.FilmsFolders)
                // ReSharper restore LoopCanBeConvertedToQuery
            {

                if (!file.FullName.Contains(movieFolder))
                    continue;

                //if (filmLocations.Any(location => location == file.FullName))
                //    return true;

                IMLItem item =
                    section.FindItemByExternalID
                        (file.FullName);

                if (item != null)
                    return true;

            }

            return false;
        }
        internal static void AddFileToIgnoredExtensions
            (FileSystemInfo file, IList<string> extensionsToIgnore,
            string audioCodec, string fileName, bool isAudio,
            bool isVideo, string videoCodec, string ext)
        {

            if (isVideo || isAudio)
                return;

            if ((ext == ".iso" || ext == ".ISO") || (ext == ".ifo" || ext == ".IFO") || (ext == ".pdf" || ext == ".PDF") ||
                (ext == ".djvu" || ext == ".DJVU")) 
                return;

            if (!Settings.EnableMediaDetection || !String.IsNullOrEmpty(videoCodec) || !String.IsNullOrEmpty(audioCodec))
                return;


            Debugger.LogMessageToFile("Thhe MediaInfo process detected that the file " + fileName +
                                      " does not contain video nor audio. The file's extension " + ext +
                                      " will be added to the ignored extensions list.");

            

            extensionsToIgnore.Add(file.Extension);

        }
        private static string[] ToStringArray(FileSystemInfo obj,
                                              IEnumerable<object> paths)
        {
            if (null == obj)
            {
                throw new ArgumentNullException("obj");
            }

            var args = new List<string>
                           {
                               obj.FullName
                           };
#if NET20
            if (ObjectExtensionMethods.IsNotNull(paths))
#else
            if (paths.IsNotNull())
#endif
            {
                var range = paths
#if NET20
                    .Where(x => ObjectExtensionMethods.IsNotNull(x))
#else
                    .Where(x => x.IsNotNull())
#endif
                    .Select(path => path.ToString().RemoveIllegalFileCharacters());
                args.AddRange(range);
            }

            return args.ToArray();
        }
 /// <summary>
 /// Deletes a file.
 /// </summary>
 /// <param name="file">The file to delete.</param>
 public static void Delete(FileSystemInfo file)
 {
     if (File.Exists(file.FullName))
     {
         File.Delete(file.FullName);
     }
 }
 public MarkdownTreeNode(FileSystemInfo location, string relativePathFromRoot, XElement markdownContent)
 {
     this.OriginalLocation = location;
     this.OriginalLocationUrl = location.ToUri();
     this.RelativePathFromRoot = relativePathFromRoot;
     this.MarkdownContent = markdownContent;
 }
Exemple #13
0
 /// <summary>
 /// Add a File/Directory to the ZipFile
 /// </summary>
 /// <param name="z">ZipFile object</param>
 /// <param name="fileSystemInfoToZip">the FileSystemInfo object to zip</param>
 public static void Add(this ZipFile z, FileSystemInfo fileSystemInfoToZip)
 {
     Add(z, new FileSystemInfo[] 
                     { 
                         fileSystemInfoToZip 
                     });
 }
        /// <summary>
        /// Calculates the FileSystemInfo object's relative path to a DirectoryInfo object
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string RelativePathOfItem(this DirectoryInfo directory, FileSystemInfo item)
        {
            Mandate.That<ArgumentNullException>(item != null);
            Mandate.That<ArgumentException>(item.FullName.Contains(directory.FullName));

            return item.FullName.Replace(directory.FullName, String.Empty).TrimStart(Path.DirectorySeparatorChar);
        }
		internal void AddFileSystemItem(FileSystemInfo f)
		{
			//if it doesn't exist, don't proceed.
			if (!f.Exists)
				return;

			AddCaseInsensitiveString(f.FullName);
			AddDateTime(f.CreationTimeUtc);
			AddDateTime(f.LastWriteTimeUtc);
			
			//check if it is a file or folder 
			var fileInfo = f as FileInfo;
			if (fileInfo != null)
			{
				AddInt(fileInfo.Length.GetHashCode());
			}
			
			var dirInfo = f as DirectoryInfo;
			if (dirInfo != null)
			{
				foreach (var d in dirInfo.GetFiles())
				{
					AddFile(d);
				}
				foreach (var s in dirInfo.GetDirectories())
				{
					AddFolder(s);
				}
			}
		}
        public static void Format(FtpCommandContext context, FileSystemInfo fileInfo, StringBuilder output)
        {
            var isFile = fileInfo is FileInfo;

            //Size
            output.AppendFormat("size={0};", isFile ? ((FileInfo)fileInfo).Length : 0);

            //Permission
            output.AppendFormat("perm={0}{1};",
                                /* Can read */ isFile ? "r" : "el",
                                /* Can write */ isFile ? "adfw" : "fpcm");
            
            //Type
            output.AppendFormat("type={0};", isFile ? "file" : "dir");

            //Create
            output.AppendFormat("create={0};", FtpDateUtils.FormatFtpDate(fileInfo.CreationTimeUtc));

            //Modify
            output.AppendFormat("modify={0};", FtpDateUtils.FormatFtpDate(fileInfo.LastWriteTimeUtc));

            //File name
            output.Append(DELIM);
            output.Append(fileInfo.Name);

            output.Append(NEWLINE);
        }
Exemple #17
0
        public static string MakeRelativePath(FileSystemInfo from, FileSystemInfo to)
        {
            if (from == null) throw new ArgumentNullException("from");
            if (to == null) throw new ArgumentNullException("to");

            return MakeRelativePath(from.FullName, to.FullName);
        }
        internal static bool VideoIsLocatedInAMovieFolder(FileSystemInfo file)
        {
            Application.DoEvents();

            bool isFilm = false;

            foreach (string filmsFolder
                in Settings.FilmsFolders)
            {

                if (String.IsNullOrEmpty
                    (filmsFolder))
                    continue;

                if (!file.FullName
                    .Contains
                    (filmsFolder))
                    continue;

                Debugger.LogMessageToFile(
                    "This video file is contained" +
                    " in the specified films root directory" +
                    " and will be considered to be a film.");

                isFilm = true;

            }

            Application.DoEvents();

            return isFilm;
        }
Exemple #19
0
 protected override Task<HttpResponseMessage> CreateItemGetResponse(FileSystemInfo info, string localFilePath)
 {
     // We don't support getting a file from the zip controller
     // Conceivably, it could be a zip file containing just the one file, but that's rarely interesting
     HttpResponseMessage notFoundResponse = Request.CreateResponse(HttpStatusCode.NotFound);
     return Task.FromResult(notFoundResponse);
 }
Exemple #20
0
        /// <summary>
        /// This function launch the restore process, with the NpgsqlConnection parameters. Restore
        /// will be done on the server and database pointed by the NpgsqlConnection
        /// </summary>
        /// <param name="connection">The NpgsqlConnection containg the database location
        /// settings</param>
        /// <param name="login">The login used to restore database</param>
        /// <param name="password">The password associed to login</param>
        /// <param name="backupFile">The backup file to restore</param>
        /// <returns>Returns a Result that tells if operation succeeds</returns>
        public Result Restore(
                                IDbConnection connection,
                                string login,
                                string password,
                                FileSystemInfo backupFile)
        {
            IPAddress connectionIpAddress = IPAddress.None;

            if (connection != null)
            {
                // TODO fix connection.Host and connection.Port
                if (IPAddress.TryParse(/*connection.Host*/ "127.0.0.1", out connectionIpAddress)
                    && (connectionIpAddress != IPAddress.None))
                {
                    return this.Restore(
                            connectionIpAddress,
                            5432, // (short)connection.Port,
                            connection.Database,
                            login,
                            password,
                            backupFile);
                }
                else
                {
                    return Result.InvalidIpAddress;
                }
            }

            return Result.InvalidNpgsqlConnection;
        }
        public SparkleMacWatcher(string path)
        {
            this.thread = new Thread (new ThreadStart (delegate {
                DateTime timestamp;
                DirectoryInfo parent = new DirectoryInfo (path);
                this.last_changed = new DirectoryInfo (path);

                while (true) {
                    timestamp = this.last_changed.LastWriteTime;
                    GetLastChange (parent);

                    if (DateTime.Compare (this.last_changed.LastWriteTime, timestamp) != 0) {
                        string relative_path = this.last_changed.FullName.Substring (path.Length + 1);

                        if (Changed != null)
                            Changed (relative_path);
                    }

                    Thread.Sleep (7500);
                    this.poll_count++;
                }
            }));

            this.thread.Start ();
        }
Exemple #22
0
    private static void DoTouch(FileSystemInfo fileSystemInfo, DateTime now)
    {
      FileAttributes fileAttributes = fileSystemInfo.Attributes;

      try
      {
        fileSystemInfo.Attributes = FileAttributes.Normal;
        fileSystemInfo.CreationTime = now;
        fileSystemInfo.LastWriteTime = now;
        fileSystemInfo.LastAccessTime = now;
      }
      catch (System.Exception e)
      {
        Console.WriteLine(e.Message);
      }
      finally
      {
        //Restore Attributes in case anything happens
        try
        {
          fileSystemInfo.Attributes = fileAttributes;
        }
        finally
        {
        }
      }
    }
Exemple #23
0
        private static int SearchInFile(FileSystemInfo file, string needle)
        {
            var byteBuffer = File.ReadAllBytes(file.FullName);

            var enc = ReadBOM(byteBuffer);

            if (!Equals(enc, Encoding.ASCII)) // if BOM is detected
            {
                var stringBuffer = enc.GetString(File.ReadAllBytes(file.FullName));
                var offset = stringBuffer.IndexOf(needle, StringComparison.InvariantCulture);

                return offset;
            }

            var encoList = new List<Encoding> // if not - search by all ways
            {
                Encoding.Default,
                Encoding.ASCII,
                Encoding.UTF8,
                Encoding.Unicode,
                Encoding.BigEndianUnicode
            };

            foreach (var enco in encoList)
            {
                var offset = enco.GetString(byteBuffer).IndexOf(needle, StringComparison.InvariantCulture);
                if (offset == -1) continue;
                return offset;
            }
            return -1;
        }
        public static unsafe HleIoDirent ConvertFileSystemInfoToHleIoDirent(FileSystemInfo FileSystemInfo)
        {
            var HleIoDirent = default(HleIoDirent);
            var FileInfo = (FileSystemInfo as FileInfo);
            var DirectoryInfo = (FileSystemInfo as DirectoryInfo);
            {
                if (DirectoryInfo != null)
                {
                    HleIoDirent.Stat.Size = 0;
                    HleIoDirent.Stat.Mode = SceMode.Directory | (SceMode)Convert.ToInt32("777", 8);
                    HleIoDirent.Stat.Attributes = IOFileModes.Directory;
                    PointerUtils.StoreStringOnPtr(FileSystemInfo.Name, Encoding.UTF8, HleIoDirent.Name);
                }
                else
                {
                    HleIoDirent.Stat.Size = FileInfo.Length;
                    HleIoDirent.Stat.Mode = SceMode.File | (SceMode)Convert.ToInt32("777", 8);
                    //HleIoDirent.Stat.Attributes = IOFileModes.File | IOFileModes.CanRead | IOFileModes.CanWrite | IOFileModes.CanExecute;
                    HleIoDirent.Stat.Attributes = IOFileModes.File;
                    PointerUtils.StoreStringOnPtr(FileSystemInfo.Name.ToUpper(), Encoding.UTF8, HleIoDirent.Name);
                }

                HleIoDirent.Stat.DeviceDependentData0 = 10;
            }
            return HleIoDirent;
        }
        public override string CheckOut(IPackageTree packageTree, FileSystemInfo destination)
        {
            SvnUpdateResult result = null;

            using (var client = new SvnClient())
            {
                try
                {
                    var svnOptions = new SvnCheckOutArgs();
                    if (UseRevision.HasValue)
                        svnOptions.Revision = new SvnRevision(UseRevision.Value);
                    client.CheckOut(new SvnUriTarget(new Uri(Url)), destination.FullName, svnOptions, out result);
                }
                catch (SvnRepositoryIOException sre)
                {
                    HandleExceptions(sre);
                }
                catch (SvnObstructedUpdateException sue)
                {
                    HandleExceptions(sue);
                }
            }

            return result.Revision.ToString();
        }
        /// <summary>
        /// Determines if the directory contains the other directory or file at any depth. 
        /// </summary>
        public static bool Contains(this DirectoryInfo dir, FileSystemInfo other)
        {
            if (dir == null) throw new ArgumentNullException("dir");
            if (other == null) throw new ArgumentNullException("other");

            return other.FullName.StartsWith(dir.FullName, true, null);
        }
Exemple #27
0
		public static string CreateRelativePathTo(this DirectoryInfo dir, FileSystemInfo file)
		{
			if (dir.FullName.EqualsIgnoreCase(file.FullName))
				return ".";
			if (file.FullName.StartsWith(dir.FullName, StringComparison.InvariantCultureIgnoreCase))
			{
				return file.FullName.ReplaceFirst(dir.FullName + "\\", "", StringComparison.InvariantCultureIgnoreCase);
			}
			else
			{
				DirectoryInfo dir2 = file as DirectoryInfo;
				if (dir2 == null)
					dir2 = ((FileInfo)file).Directory;
				var dirPath = dir.GetPath();
				var dir2Path = dir2.GetPath();
				while (dirPath.Peek() == dir2Path.Peek())
				{
					dirPath.Pop();
					dir2Path.Pop();
				}
				var final = dirPath.Peek().FullName;
				foreach (var p in dirPath)
				{
					final = Path.Combine(final, "..");
				}
				foreach (var p in dir2Path)
				{
					final = Path.Combine(final, p.Name);
				}
				if (file is FileInfo)
					final = Path.Combine(final, ((FileInfo)file).Name);
				return final;
			}
		}
 public FileGroupInfo(FileSystemInfo _main, FileGroupInfoType _type)
 {
     main = _main;
     type = _type;
     files = new List<FileSystemInfo>();
     numbers = new Dictionary<FileSystemInfo, uint>();
 }
Exemple #29
0
        public MovieFileViewModel(System.IO.FileSystemInfo sysFile)
        {
            if (SysTemConfiger.ExceptShowFile.Exists(l => l == sysFile.Extension))
            {
                return;
            }

            if (sysFile is FileInfo)
            {
                FileInfo file = sysFile as FileInfo;
                this.FileName = sysFile.Name;
                this.FilePath = sysFile.FullName;
                this.IsFile   = true;
                this.Size     = file.Length;
            }
            else
            {
                this.FileName = sysFile.Name;
                this.FilePath = sysFile.FullName;
                this.IsFile   = false;
            }

            this.LastTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

            RelayCommand = new RelayCommand(new Action <object>(ButtonClickFunc));

            this.RefreshImage();
        }
Exemple #30
0
        public Item(FileSystemInfo info)
        {
            Id = Guid.NewGuid().ToString();
            Name = info.Name;
            Created = info.CreationTime;
            Modified = info.LastWriteTime;
            LastAccess = info.LastAccessTime;

            var fileInfo = info as FileInfo;
            if (fileInfo != null)
            {
                m_isReadOnly = fileInfo.IsReadOnly;
                Size = fileInfo.Length;
                IsFile = true;
            }
            else
            {
                IsFile = false;
            }
            FileSecurity fs = File.GetAccessControl(info.FullName);
            var sidOwning = fs.GetOwner(typeof(SecurityIdentifier));
            var ntAccount = sidOwning.Translate(typeof(NTAccount));
            Owner = ntAccount.Value;

            // todo: it's not so important, but still put here something like read, write etc.
            var sidRules = fs.GetAccessRules(true, true, typeof(SecurityIdentifier));
            List<string> rulesList = new List<string>(sidRules.Count);
            for (int i = 0; i < sidRules.Count; i++)
            {
                rulesList.Add(sidRules[i].IdentityReference.Value);
            }
            Rights = string.Join("; ", rulesList);
        }
 private static string EncodeItem(FileSystemInfo file)
 {
     var name = Path.GetFileNameWithoutExtension(file.Name);
     var value = File.ReadAllText(file.FullName);
     var item = new { Name = name, Value = value };
     return Json.Encode(item);
 }
Exemple #32
0
        static string GetDirFileString(int level, System.IO.FileSystemInfo dirfile)
        {
            //char l0 = '+'; Пробовал с символами псвдографики, без них понравилось больше
            //char l1 = '\u251C';// ├
            //char l2 = '\u2500';// ─
            //char l02 = '\u2502';// │
            //char l3 = '\u2514'; //└
            string indent         = level == 0 ? "" : "  ";
            char   horizLine      = Properties.Settings.Default.HorizLines ? '-' : ' ';
            int    mode           = Properties.Settings.Default.ViewMode;
            int    maxFileNameLen = Const.GetMaxFileNameLen(mode);
            string s = indent + dirfile.Name;

            if (s.Length > maxFileNameLen)
            {
                s = s.Substring(0, maxFileNameLen - 3) + Str.tooLongString; //если длина строки больше ширины колонки
            }
            s = s.PadRight(maxFileNameLen, horizLine);                      //колонка 1
            if (mode > 0)
            {
                string s1;
                if (dirfile.GetType() == typeof(System.IO.FileInfo))
                {
                    System.IO.FileInfo f = (System.IO.FileInfo)dirfile;
                    s1 = Str.GetSizeString(f.Length);
                }
                else
                {
                    s1 = Str.directory;
                }
                s1 = s1.PadRight(Const.sizeStringLen); //колонка 2
                s += s1;
            }
            if (mode > 1)
            {
                string s1 = Str.GetFileAttributesString(dirfile.Attributes);
                s1 = s1.PadRight(Const.attrStringLen); //колонка 3
                s += s1;
            }
            if (mode > 2)
            {
                string s1 = dirfile.CreationTime.ToString(Str.dateTimePatt);
                s1 = s1.PadRight(Const.timeStringLen); //колонка 4
                s += s1;
            }
            if (mode > 3)
            {
                string s1 = dirfile.LastAccessTime.ToString(Str.dateTimePatt);
                s1 = s1.PadRight(Const.timeStringLen); //колонка 5
                s += s1;
            }
            if (mode > 4)
            {
                string s1 = dirfile.LastWriteTime.ToString(Str.dateTimePatt);
                s1 = s1.PadRight(Const.timeStringLen); //колонка 6
                s += s1;
            }
            return(s);
        }
Exemple #33
0
 private static void CopyFolder(string strSources, string strDest)
 {
     System.IO.DirectoryInfo    directoryInfo   = new System.IO.DirectoryInfo(strSources);
     System.IO.FileSystemInfo[] fileSystemInfos = directoryInfo.GetFileSystemInfos();
     for (int i = 0; i < fileSystemInfos.Length; i++)
     {
         System.IO.FileSystemInfo fileSystemInfo = fileSystemInfos[i];
         string text = System.IO.Path.Combine(strDest, fileSystemInfo.Name);
         if (fileSystemInfo is System.IO.FileInfo)
         {
             System.IO.File.Copy(fileSystemInfo.FullName, text, true);
         }
         else
         {
             System.IO.Directory.CreateDirectory(text);
             FileUtils.CopyFolder(fileSystemInfo.FullName, text);
         }
     }
 }
        public static string SetAttributes(this System.IO.FileSystemInfo __file)
        {
            string attributes = "";

            if (__file.Attributes.HasFlag(FileAttributes.ReadOnly))
            {
                attributes += "r";
            }
            else
            {
                attributes += "-";
            }

            if (__file.Attributes.HasFlag(FileAttributes.Archive))
            {
                attributes += "a";
            }
            else
            {
                attributes += "-";
            }

            if (__file.Attributes.HasFlag(FileAttributes.Hidden))
            {
                attributes += "h";
            }
            else
            {
                attributes += "-";
            }

            if (__file.Attributes.HasFlag(FileAttributes.System))
            {
                attributes += "s";
            }
            else
            {
                attributes += "-";
            }

            return(attributes);
        }
Exemple #35
0
        //public void RemoveLayersfromTOC(string directory)
        //{
        //    //IMxDocument mxMap = (IMxDocument)application.Document;
        //    //IMap pMap = mxMap.FocusMap;
        //    //IMapLayers pMapLayers = pMap;

        //    for (int i = 0; i <= ArcMap.Document.FocusMap.LayerCount - 1; i++)
        //    {
        //        ILayer player = ArcMap.Document.FocusMap.Layer[i];
        //        if (player is IGroupLayer)
        //        {
        //            RemoveLayersfromGroupLayer((IGroupLayer)player, directory);
        //        }
        //        else
        //        {
        //            IDataset pDS = player;
        //            try
        //            {
        //                if (LCase(directory) == LCase(pDS.Workspace.PathName))
        //                {
        //                    pMap.DeleteLayer(player);
        //                }
        //            }
        //            }

        //        if (player != null)
        //        {
        //            System.Runtime.InteropServices.Marshal.ReleaseComObject(player);
        //            player = null;
        //        }
        //    }

        //    mxMap.UpdateContents();
        //    mxMap.ActiveView.Refresh();
        //    ESRI.ArcGIS.ArcMapUI.IContentsView pContentsView = mxMap.CurrentContentsView;
        //    pContentsView.Refresh(null);
        //    if (mxMap != null)
        //    {
        //        System.Runtime.InteropServices.Marshal.ReleaseComObject(mxMap);
        //        mxMap = null;
        //    }

        //    if (pContentsView != null)
        //    {
        //        System.Runtime.InteropServices.Marshal.ReleaseComObject(pContentsView);
        //        pContentsView = null;
        //    }
        //}

        //public void RemoveLayersfromGroupLayer(IGroupLayer pGroupLayer, string directory)
        //{
        //    ILayer pLayer;
        //    List<ILayer> LayersToDelete = new List<ILayer>();
        //    ICompositeLayer pCompositeLayer = (ICompositeLayer)pGroupLayer;
        //    for (int i = 1; i <= pCompositeLayer.Count; i++)
        //    {
        //        pLayer = pCompositeLayer.Layer[i - 1];
        //        if (pLayer is IGroupLayer)
        //        {
        //            RemoveLayersfromGroupLayer(pLayer, directory);
        //        }
        //        else
        //        {
        //            try
        //            {
        //                IDataset pDS = (IDataset)pLayer;
        //                string LayerDirectoryname = pDS.Workspace.PathName.ToLower();
        //                if (LayerDirectoryname.EndsWith(IO.Path.DirectorySeparatorChar))
        //                {
        //                    LayerDirectoryname = LayerDirectoryname.Substring(0, LayerDirectoryname.Length - 1);
        //                }

        //                if (LCase(directory) == LayerDirectoryname)
        //                {
        //                    LayersToDelete.Add(pLayer);
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                Debug.WriteLine(ex.Message);
        //            }
        //        }
        //    }

        //    foreach (ILayer pDeleteLayer in LayersToDelete)
        //    {
        //        pGroupLayer.Delete(pDeleteLayer);
        //        if (pDeleteLayer != null)
        //        {
        //            System.Runtime.InteropServices.Marshal.ReleaseComObject(pDeleteLayer);
        //            pDeleteLayer = null;
        //        }
        //    }

        //    if (pGroupLayer != null)
        //    {
        //        System.Runtime.InteropServices.Marshal.ReleaseComObject(pGroupLayer);
        //        pGroupLayer = null;
        //    }
        //}

        //public void RemoveGroupLayer(string sGroupLayerName)
        //{
        //    IMap pMap = ArcMap.Document.FocusMap;
        //    UID pUID = new UID();
        //    pUID.Value = "{EDAD6644-1810-11D1-86AE-0000F8751720}";

        //    IEnumLayer pEnum = ArcMap.Document.FocusMap.Layers[pUID, true];
        //    ILayer pL = pEnum.Next();
        //    while (pL is ILayer)
        //    {
        //        if (string.Compare(sGroupLayerName, pL.Name, true) == 0)
        //        {
        //            pMap.DeleteLayer(pL);
        //        }

        //        pL = pEnum.Next();
        //    }
        //}


        public static IRasterLayer IsRasterLayerInGroupLayer(System.IO.FileSystemInfo rasterPath, IGroupLayer pGrpLyr)
        {
            ICompositeLayer compositeLayer = pGrpLyr as ICompositeLayer;

            if (compositeLayer != null & compositeLayer.Count > 0)
            {
                for (int i = 0; i <= compositeLayer.Count - 1; i++)
                {
                    if (compositeLayer.Layer[i] is IRasterLayer)
                    {
                        IRasterLayer pLayer = (IRasterLayer)compositeLayer.Layer[i];
                        if (string.Compare(pLayer.FilePath, rasterPath.FullName, true) == 0)
                        {
                            return(pLayer);
                        }
                    }
                }
            }

            return(null);
        }
        public FileBindModel(System.IO.FileSystemInfo sysFile)
        {
            if (SysTemConfiger.ExceptShowFile.Exists(l => l == sysFile.Extension))
            {
                return;
            }

            if (sysFile is FileInfo)
            {
                this.FileName = sysFile.Name;
                this.FilePath = sysFile.FullName;
                this.IsFile   = true;
            }
            else
            {
                this.FileName = sysFile.Name;
                this.FilePath = sysFile.FullName;
                this.IsFile   = false;
            }

            this.LastTime = DateTime.Now;
        }
Exemple #37
0
 public WrappedFileInfo(FSI fsi) => this.fsi = fsi;
Exemple #38
0
 private static ExclusiveLock CreateFileSystemLock(System.IO.FileSystemInfo fileSystemInfo)
 {
     Platform.CheckForNullReference(fileSystemInfo, "fileSystemInfo");
     return(CreateFileSystemLock(fileSystemInfo.FullName));
 }
 public static string get_FullName(System.IO.FileSystemInfo aThis)
 {
     return("FullName not implemented yet in FileSystemInfo plug");
 }
Exemple #40
0
 protected StorageItem(SysIO.FileSystemInfo item)
 {
     BaseStorageItem = item ?? throw new ArgumentNullException(nameof(item));
 }
Exemple #41
0
        public void SetAttributes(string path, FileAttributes attributes)
        {
            // Validate that only flags from the attribute are being provided.  This is an
            // approximation for the validation done by the Win32 function.
            const FileAttributes allValidFlags =
                FileAttributes.Archive | FileAttributes.Compressed | FileAttributes.Device |
                FileAttributes.Directory | FileAttributes.Encrypted | FileAttributes.Hidden |
                FileAttributes.IntegrityStream | FileAttributes.Normal | FileAttributes.NoScrubData |
                FileAttributes.NotContentIndexed | FileAttributes.Offline | FileAttributes.ReadOnly |
                FileAttributes.ReparsePoint | FileAttributes.SparseFile | FileAttributes.System |
                FileAttributes.Temporary;

            if ((attributes & ~allValidFlags) != 0)
            {
                // Using constant string for argument to match historical throw
                throw new ArgumentException(SR.Arg_InvalidFileAttrs, "Attributes");
            }

            EnsureStatInitialized(path);

            if (!_exists)
            {
                FileSystemInfo.ThrowNotFound(path);
            }

            if (Interop.Sys.CanSetHiddenFlag)
            {
                if ((attributes & FileAttributes.Hidden) != 0)
                {
                    if ((_fileStatus.UserFlags & (uint)Interop.Sys.UserFlags.UF_HIDDEN) == 0)
                    {
                        // If Hidden flag is set and cached file status does not have the flag set then set it
                        Interop.CheckIo(Interop.Sys.LChflags(path, (_fileStatus.UserFlags | (uint)Interop.Sys.UserFlags.UF_HIDDEN)), path, InitiallyDirectory);
                    }
                }
                else
                {
                    if ((_fileStatus.UserFlags & (uint)Interop.Sys.UserFlags.UF_HIDDEN) == (uint)Interop.Sys.UserFlags.UF_HIDDEN)
                    {
                        // If Hidden flag is not set and cached file status does have the flag set then remove it
                        Interop.CheckIo(Interop.Sys.LChflags(path, (_fileStatus.UserFlags & ~(uint)Interop.Sys.UserFlags.UF_HIDDEN)), path, InitiallyDirectory);
                    }
                }
            }

            // The only thing we can reasonably change is whether the file object is readonly by changing permissions.

            int newMode = _fileStatus.Mode;

            if ((attributes & FileAttributes.ReadOnly) != 0)
            {
                // Take away all write permissions from user/group/everyone
                newMode &= ~(int)(Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IWOTH);
            }
            else if ((newMode & (int)Interop.Sys.Permissions.S_IRUSR) != 0)
            {
                // Give write permission to the owner if the owner has read permission
                newMode |= (int)Interop.Sys.Permissions.S_IWUSR;
            }

            // Change the permissions on the file
            if (newMode != _fileStatus.Mode)
            {
                Interop.CheckIo(Interop.Sys.ChMod(path, newMode), path, InitiallyDirectory);
            }

            _fileStatusInitialized = -1;
        }
 public FileSystemEntry(FileSystemEntry parent, System.IO.FileSystemInfo systemFileInfo)
 {
     Parent = parent;
     Name   = systemFileInfo.Name;
     this.systemFileInfo = systemFileInfo;
 }
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="name"></param>
 /// <param name="fi"></param>
 /// <param name="img_idx"></param>
 /// <param name="sel_img"></param>
 public FileTreeNode(string key, string name, FileSystemInfo fi, int img_idx, int sel_img)
     : base(key, name, img_idx, sel_img)
 {
     this.fi = fi;
     InitializeRoot();
 }
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="name"></param>
 /// <param name="fi"></param>
 public FileTreeNode(string key, string name, FileSystemInfo fi)
     : base(key, name)
 {
     this.fi = fi;
     InitializeRoot();
 }
Exemple #45
0
        private unsafe void SetAccessOrWriteTimeCore(string path, DateTimeOffset time, bool isAccessTime, bool checkCreationTime, bool asDirectory)
        {
            // This api is used to set creation time on non OSX platforms, and as a fallback for OSX platforms.
            // The reason why we use it to set 'creation time' is the below comment:
            // Unix provides APIs to update the last access time (atime) and last modification time (mtime).
            // There is no API to update the CreationTime.
            // Some platforms (e.g. Linux) don't store a creation time. On those platforms, the creation time
            // is synthesized as the oldest of last status change time (ctime) and last modification time (mtime).
            // We update the LastWriteTime (mtime).
            // This triggers a metadata change for FileSystemWatcher NotifyFilters.CreationTime.
            // Updating the mtime, causes the ctime to be set to 'now'. So, on platforms that don't store a
            // CreationTime, GetCreationTime will return the value that was previously set (when that value
            // wasn't in the future).

            // force a refresh so that we have an up-to-date times for values not being overwritten
            InvalidateCaches();
            EnsureCachesInitialized(path);

            if (!EntryExists)
            {
                FileSystemInfo.ThrowNotFound(path);
            }

            // we use utimes()/utimensat() to set the accessTime and writeTime
            Interop.Sys.TimeSpec *buf = stackalloc Interop.Sys.TimeSpec[2];

            long seconds     = time.ToUnixTimeSeconds();
            long nanoseconds = UnixTimeSecondsToNanoseconds(time, seconds);

#if TARGET_BROWSER
            buf[0].TvSec  = seconds;
            buf[0].TvNsec = nanoseconds;
            buf[1].TvSec  = seconds;
            buf[1].TvNsec = nanoseconds;
#else
            if (isAccessTime)
            {
                buf[0].TvSec  = seconds;
                buf[0].TvNsec = nanoseconds;
                buf[1].TvSec  = _fileCache.MTime;
                buf[1].TvNsec = _fileCache.MTimeNsec;
            }
            else
            {
                buf[0].TvSec  = _fileCache.ATime;
                buf[0].TvNsec = _fileCache.ATimeNsec;
                buf[1].TvSec  = seconds;
                buf[1].TvNsec = nanoseconds;
            }
#endif
            Interop.CheckIo(Interop.Sys.UTimensat(path, buf), path, asDirectory);

            // On OSX-like platforms, when the modification time is less than the creation time (including
            // when the modification time is already less than but access time is being set), the creation
            // time is set to the modification time due to the api we're currently using; this is not
            // desirable behaviour since it is inconsistent with windows behaviour and is not logical to
            // the programmer (ie. we'd have to document it), so these api calls revert the creation time
            // when it shouldn't be set (since we're setting modification time and access time here).
            // checkCreationTime is only true on OSX-like platforms.
            // allowFallbackToLastWriteTime is ignored on non OSX-like platforms.
            bool updateCreationTime = checkCreationTime && (_fileCache.Flags & Interop.Sys.FileStatusFlags.HasBirthTime) != 0 &&
                                      (buf[1].TvSec < _fileCache.BirthTime || (buf[1].TvSec == _fileCache.BirthTime && buf[1].TvNsec < _fileCache.BirthTimeNsec));

            InvalidateCaches();

            if (updateCreationTime)
            {
                Interop.Error error = SetCreationTimeCore(path, _fileCache.BirthTime, _fileCache.BirthTimeNsec);
                if (error != Interop.Error.SUCCESS && error != Interop.Error.ENOTSUP)
                {
                    Interop.CheckIo(error, path, asDirectory);
                }
            }
        }
Exemple #46
0
 private static void ExtractBackup(FileSystemInfo file, string extractionDirectory)
 {
     ZipFile.ExtractToDirectory(file.FullName, extractionDirectory);
 }
        /// <summary>
        /// Combines the screenshots into one contiguous screenshot
        /// </summary>
        /// <param name="files">The files (images) to combine</param>
        /// <param name="e">For UX, an output progress message</param>
        public static void CombineScreenshot(FileSystemInfo[] files, WaitWindowEventArgs e)
        {
           

            string screenshotLocation = Path.Combine(Constants.CacheLocation, "temp.png");

            using (MagickImageCollection images = new MagickImageCollection())
            {
                // Add the first image
                var orderedFiles = files.OrderBy(f => f.CreationTime);
                foreach (FileSystemInfo file in orderedFiles)
                {
                    MagickImage first = new MagickImage(file.FullName);
                    e.Window.Message = "Obtaining Snapshots... Please Wait";
                    images.Add(first);
                }

                using (MagickImage result = images.AppendVertically())
                {
                    e.Window.Message = "Building Screenshot... Please Wait" + System.Environment.NewLine + "This can take a minute.";
                    try
                    {
                        result.Write(screenshotLocation);
                    } catch (MagickImageErrorException err)
                    {
                        Debug.WriteLine($"Error: {err}");
                    }
                   
                }
        
            }
        }