/// <summary>
        /// Выполняет одно из действий с указанным файлом, в зависимости от выбраного действия.
        /// Перемещение, удаление, переиминование и перемещение, перемещение дубликата.
        /// </summary>
        /// <param name="filePath">Путь к файлу, с которым нужно выполнить действие.</param>
        /// <param name="action">Возможное действие с файлом. Объект enum-типа FileActionType.</param>
        public static string FileMoveOrDelete(string filePath, FileActionType action)
        {
            switch (action)
            {
            case Delete:
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    return(null);
                }
                return(null);

            case Move:
                if (File.Exists(filePath))
                {
                    var newFilePath = ProgramSettings.GetInstance().ReplacePath + Path.GetFileName(filePath);
                    File.Move(filePath, newFilePath);
                    File.Delete(filePath);
                    return(newFilePath);
                }
                return(null);

            case RenameAndMove:
                if (File.Exists(filePath))
                {
                    var newFilePath = MakeNewFilePath(filePath);
                    File.Move(filePath, newFilePath);
                    File.Delete(filePath);
                    return(newFilePath);
                }
                return(null);

            case MoveDuplicate:
                if (File.Exists(filePath))
                {
                    var duplicateDirectory = ProgramSettings.GetInstance().ReplacePath + "/Duplicate";
                    if (Directory.Exists(duplicateDirectory))
                    {
                        var newFilePath = duplicateDirectory + "/" + Path.GetFileName(filePath);
                        File.Move(filePath, newFilePath);
                        File.Delete(filePath);
                    }
                    else
                    {
                        Directory.CreateDirectory(duplicateDirectory);
                        var newFilePath = duplicateDirectory + "/" + Path.GetFileName(filePath);
                        File.Move(filePath, newFilePath);
                        File.Delete(filePath);
                    }

                    return(null);
                }
                return(null);

            default:
                throw new ArgumentOutOfRangeException(nameof(action), action, null);
            }
        }
示例#2
0
        public virtual async Task RunPaths(IEnumerable <string> paths, int index, FileActionType type)
        {
            var handlers = this.GetHandlers(paths, type);

            foreach (var pair in handlers)
            {
                await pair.Key.Handle(pair.Value, index, type).ConfigureAwait(false);
            }
        }
示例#3
0
        private static FileActionData CreateFileActionData(FileActionType type, string fileName, string newName = null)
        {
            var data = new FileActionData
            {
                FileActionType = type,
                FileName       = fileName,
                NewFileName    = newName
            };

            return(data);
        }
示例#4
0
        /// <summary>
        /// 临时目录转到正式目录并补全绝对路径
        /// </summary>
        public string CombinePicUrl(string pic, DateTime date, FileActionType fileActionType)
        {
            if (string.IsNullOrEmpty(pic))
            {
                return("");
            }

            pic = ChangePicDir(pic, date, fileActionType);

            pic = AppConfig.ImageBaseUrl.TrimEnd('/') + "/" + pic.TrimStart('/');
            return(pic);
        }
示例#5
0
 public bool CanHandle(string path, FileActionType type)
 {
     if (type != FileActionType.Library)
     {
         return(false);
     }
     if (!Directory.Exists(path) && !this.PlaybackManager.IsSupported(path))
     {
         return(false);
     }
     return(true);
 }
示例#6
0
        public Task Handle(IEnumerable <string> paths, FileActionType type)
        {
            switch (type)
            {
            case FileActionType.Library:
                return(this.Add(paths));
            }
#if NET40
            return(TaskEx.FromResult(false));
#else
            return(Task.CompletedTask);
#endif
        }
 public async Task Handle(IEnumerable <string> paths, FileActionType type)
 {
     switch (type)
     {
     case FileActionType.Playlist:
         var playlist = this.PlaylistManager.CurrentPlaylist ?? this.PlaylistManager.SelectedPlaylist;
         foreach (var path in paths)
         {
             await this.OpenArchive(playlist, path).ConfigureAwait(false);
         }
         break;
     }
 }
示例#8
0
        public Task Handle(IEnumerable <string> paths, FileActionType type)
        {
            switch (type)
            {
            case FileActionType.Playlist:
                return(this.Add(this.SelectedPlaylist, paths, false));
            }
#if NET40
            return(TaskEx.FromResult(false));
#else
            return(Task.CompletedTask);
#endif
        }
        public Task Handle(IEnumerable <string> paths, int index, FileActionType type)
        {
            switch (type)
            {
            case FileActionType.Playlist:
                var playlist = this.PlaylistManager.CurrentPlaylist ?? this.PlaylistManager.SelectedPlaylist;
                return(this.AddArchivesToPlaylist(playlist, index, paths));
            }
#if NET40
            return(TaskEx.FromResult(false));
#else
            return(Task.CompletedTask);
#endif
        }
 public bool CanHandle(string path, FileActionType type)
 {
     if (!this.Enabled)
     {
         return(false);
     }
     if (type != FileActionType.Playlist)
     {
         return(false);
     }
     if (!File.Exists(path) || !string.Equals(Path.GetExtension(path), CUE, StringComparison.OrdinalIgnoreCase))
     {
         return(false);
     }
     return(true);
 }
 public bool CanHandle(string path, FileActionType type)
 {
     if (!this.Enabled)
     {
         return(false);
     }
     if (type != FileActionType.Playlist)
     {
         return(false);
     }
     if (!File.Exists(path) || !ArchiveUtils.Extensions.Contains(path.GetExtension(), StringComparer.OrdinalIgnoreCase))
     {
         return(false);
     }
     return(true);
 }
        public virtual async Task RunPaths(IEnumerable <string> paths, FileActionType type)
        {
            var handlers = new Dictionary <IFileActionHandler, IList <string> >();

            foreach (var path in paths)
            {
                foreach (var handler in this.FileActionHandlers)
                {
                    if (!handler.CanHandle(path, type))
                    {
                        continue;
                    }
                    handlers.GetOrAdd(handler, key => new List <string>()).Add(path);
                }
            }
            foreach (var pair in handlers)
            {
                await pair.Key.Handle(pair.Value, type).ConfigureAwait(false);
            }
        }
示例#13
0
 public FileActionEventArgs(FileActionType action, UniFile file, object tag = null)
 {
     Action = action;
     File = file;
     Tag = tag;
 }
        protected void UpdateLayoutInfo(FileActionType action)
        {
            string baseDirForInfoFile = null;

            baseDirForInfoFile = System.IO.Path.Combine(_AssemblyBasePath, _ConfiguredPathForLayouts);
            baseDirForInfoFile = System.IO.Path.Combine(baseDirForInfoFile, _ClassNameAsFolder);
            Logger.Debug("Base path for layouts => [{0}]", baseDirForInfoFile);

            //Check if the above path exists or not
            if (System.IO.Directory.Exists(baseDirForInfoFile))
            {
                Logger.Debug("Base path for layouts found; Trying to locate *.inf files");

                //lookout for info file
                string[] files = System.IO.Directory.GetFiles(baseDirForInfoFile, "*" + _InfoFileExtension);
                if (files.Length > 0)
                {
                    Logger.Debug("[{0}] layout's .inf file(s) found", files.Length);

                    if (action == FileActionType.Read || action == FileActionType.Open)
                    {
                        Logger.Debug("Layout's information load action started...");

                        //If path exists, check for the info file
                        YamlDotNet.Serialization.Deserializer deserializer = new YamlDotNet.Serialization.Deserializer();
                        Logger.Debug("Reading info data from file [{0}]", files[0]);

                        using (System.IO.TextReader reader = System.IO.File.OpenText(files[0])) {
                            LayoutInfo = deserializer.Deserialize <LayoutInformation>(reader);
                        }

                        Logger.Debug("Layout's information has been loaded successfully");

                        baseElement.Id   = LayoutInfo.Id;
                        baseElement.Name = LayoutInfo.Name;
                        PathToXml        = LayoutInfo.PathToXml;
                    }
                    else if (action == FileActionType.Write || action == FileActionType.Save)
                    {
                        Logger.Debug("Layout's information update started...");

                        //Let's make sure that "LayoutInfo" field has all the updated info
                        //before we store it back to database
                        _LayoutXmlFileName   = Id + "_Layout" + _LayoutFileExtension;
                        LayoutInfo.Id        = Id;
                        LayoutInfo.Name      = Name;
                        LayoutInfo.PathToXml = PathToXml = System.IO.Path.Combine(
                            System.IO.Path.Combine(
                                System.IO.Path.Combine(_AssemblyBasePath,
                                                       _ConfiguredPathForLayouts),
                                _ClassNameAsFolder),
                            _LayoutXmlFileName);

                        //Save the info in YAML format
                        YamlDotNet.Serialization.Serializer serializer = new YamlDotNet.Serialization.Serializer();
                        System.IO.StringWriter strWriter = new System.IO.StringWriter();
                        serializer.Serialize(strWriter, LayoutInfo);

                        //Delete old info file, recalculate info file name (might have changed if layout Name
                        // is changed) and save the file back with latest information
                        System.IO.File.Delete(files[0]);
                        Logger.Debug("Existing info file has been deleted => [{0}]", files[0]);

                        _InfoFileName = this.Name.Replace(' ', '_') + "_Info" + _InfoFileExtension;
                        Logger.Debug("Layout information save file path => [{0}]", _InfoFileName);

                        using (System.IO.TextWriter writer = System.IO.File.CreateText(System.IO.Path.Combine(baseDirForInfoFile, _InfoFileName))) {
                            writer.Write(strWriter.ToString());
                        }

                        Logger.Debug("Layout's information updated successfully to [{0}]", System.IO.Path.Combine(baseDirForInfoFile, _InfoFileName));
                    }
                    else
                    {
                        Logger.Debug("Invalid action specified for this operation => [{0}]", action);
                    }
                }
                else
                {
                    //File not found
                    Logger.Debug("Unable to find layout info file; New file will be created...");

                    //Since no info file found, assign a new Name to the layout
                    if (Id == Guid.Empty)
                    {
                        baseElement.Id   = LayoutInfo.Id = Guid.NewGuid();
                        baseElement.Name = LayoutInfo.Name = Get.i.Names.GetName("Layout");
                        Logger.Debug("Assigned Id={0}, Name={1}", Id, Name);
                    }

                    _LayoutXmlFileName = this.Id + "_Layout" + _LayoutFileExtension;
                    Logger.Debug("Layout's Xml file name => [{0}]", _LayoutXmlFileName);

                    PathToXml = LayoutInfo.PathToXml = System.IO.Path.Combine(
                        System.IO.Path.Combine(
                            System.IO.Path.Combine(_AssemblyBasePath,
                                                   _ConfiguredPathForLayouts),
                            _ClassNameAsFolder),
                        _LayoutXmlFileName);

                    _InfoFileName = this.Name.Replace(' ', '_') + "_Info" + _InfoFileExtension;
                    Logger.Debug("Layout information save file path => [{0}]", _InfoFileName);

                    //Save the info in YAML format
                    YamlDotNet.Serialization.Serializer serializer = new YamlDotNet.Serialization.Serializer();
                    System.IO.StringWriter strWriter = new System.IO.StringWriter();
                    serializer.Serialize(strWriter, LayoutInfo);
                    using (System.IO.TextWriter writer = System.IO.File.CreateText(System.IO.Path.Combine(baseDirForInfoFile, _InfoFileName))) {
                        writer.Write(strWriter.ToString());
                    }

                    Logger.Debug("Layout's information file created and saved successfully");
                }
            }
            else
            {
                Logger.Debug("Layout's base directory not found; New directory will be created...");
                //No dir exists, try to create one
                System.IO.DirectoryInfo dirInfo = System.IO.Directory.CreateDirectory(baseDirForInfoFile);

                //Since no dir and info files exists, assign a new Name to layout
                if (baseElement.Id == Guid.Empty)
                {
                    baseElement.Id   = LayoutInfo.Id = Guid.NewGuid();
                    baseElement.Name = LayoutInfo.Name = Get.i.Names.GetName("Layout");
                    Logger.Debug("Assigned Id={0}, Name={1}", Id, Name);
                }

                _LayoutXmlFileName = this.Id + "_Layout" + _LayoutFileExtension;
                Logger.Debug("Layout's Xml file name => [{0}]", _LayoutXmlFileName);

                PathToXml = LayoutInfo.PathToXml = System.IO.Path.Combine(
                    System.IO.Path.Combine(
                        System.IO.Path.Combine(_AssemblyBasePath,
                                               _ConfiguredPathForLayouts),
                        _ClassNameAsFolder),
                    _LayoutXmlFileName);

                _InfoFileName = this.Name.Replace(' ', '_') + "_Info" + _InfoFileExtension;
                Logger.Debug("Layout information save file path => [{0}]", _InfoFileName);

                //Save the info in YAML format
                YamlDotNet.Serialization.Serializer serializer = new YamlDotNet.Serialization.Serializer();
                System.IO.StringWriter strWriter = new System.IO.StringWriter();
                serializer.Serialize(strWriter, LayoutInfo);
                using (System.IO.TextWriter writer = System.IO.File.CreateText(System.IO.Path.Combine(dirInfo.FullName, _InfoFileName))) {
                    writer.Write(strWriter.ToString());
                }

                Logger.Debug("Layout's base directory & file created and saved successfully");
            }
        }
示例#15
0
 public FileAction(string filePath, FileActionType type, string oldFilePath) : this(filePath, type)
 {
     OldFilePath = oldFilePath;
 }
示例#16
0
 public FileAction(string filePath, FileActionType type)
 {
     ActionType = type;
     FilePath   = filePath ?? throw new ArgumentNullException(nameof(filePath));
 }
示例#17
0
 public Task Handle(IEnumerable <string> paths, int index, FileActionType type)
 {
     throw new NotImplementedException();
 }
示例#18
0
        private void InvokeFileActionEvent(FileActionType type, string fullName, string newName = null)
        {
            var data = CreateFileActionData(type, fullName, newName);

            FileActionEvent?.Invoke(data);
        }
 public RecupDirSorter(string rootRecupDirPath, FileActionType fileActionType, int maxFilesPerSortedDir = 500)
 {
     RootRecupDir         = rootRecupDirPath;
     FileActionType       = fileActionType;
     MaxFilesPerSortedDir = maxFilesPerSortedDir;
 }
示例#20
0
        protected virtual IDictionary <IFileActionHandler, IList <string> > GetHandlers(IEnumerable <string> paths, FileActionType type)
        {
            var handlers = new Dictionary <IFileActionHandler, IList <string> >();

            foreach (var path in paths)
            {
                foreach (var handler in this.FileActionHandlers)
                {
                    if (!handler.CanHandle(path, type))
                    {
                        continue;
                    }
                    handlers.GetOrAdd(handler, key => new List <string>()).Add(path);
                }
            }
            return(handlers);
        }
示例#21
0
        private string ChangePicDir(string pic, DateTime date, FileActionType fileActionType)
        {
            string dir          = FileService.GetPhysicsRootDir();
            string saveFilePath = FileService.TempDir;

            if (fileActionType == FileActionType.身份证反面图片 || fileActionType == FileActionType.身份证正面图片 || fileActionType == FileActionType.百度人脸识别图片)
            {
                saveFilePath = FileService.UserAuthDir;
            }
            else if (fileActionType == FileActionType.意见反馈)
            {
                saveFilePath = FileService.UserFeedback;
            }
            else if (fileActionType == FileActionType.用户头像)
            {
                saveFilePath = FileService.UserPhotoDir;
            }
            else if (fileActionType == FileActionType.驾驶证行驶证 || fileActionType == FileActionType.驾驶证副页)
            {
                saveFilePath = FileService.DriverLicense;
            }
            string destDir = Path.Combine(dir, saveFilePath, date.ToString("yyyyMMdd"));

            if (!Directory.Exists(destDir))
            {
                try
                {
                    Directory.CreateDirectory(destDir);
                }
                catch (Exception ex)
                {
                    log.Info("创建目录失败," + destDir, ex);
                }
            }
            pic = pic.TrimStart('/').Replace(AppConfig.FileRootDir, "").Replace("/", "\\");
            string srcFile  = Path.Combine(dir, pic);
            string destFile = Path.Combine(destDir, Path.GetFileName(pic));

            if (srcFile.Replace("\\", "/").Equals(destFile.Replace("\\", "/"), StringComparison.OrdinalIgnoreCase))
            {
                return(pic.Replace("\\", "/"));
            }
            try
            {
                if (File.Exists(srcFile))
                {
                    File.Move(srcFile, destFile);
                }
            }
            catch (Exception ex)
            {
                log.Info($"Move文件失败,马上再次尝试Copy,{srcFile}->{destFile}", ex);
                try
                {
                    File.Copy(srcFile, destFile);
                    log.Info($"Copy文件成功,{srcFile}->{destFile}");
                }
                catch (Exception ex2)
                {
                    log.Info($"Copy文件也失败,直接返回临时目录文件,{srcFile}->{destFile}", ex2);
                    return(srcFile.Replace(dir, "").Replace("\\", "/"));
                }
            }
            return(destFile.Replace(dir, "").Replace("\\", "/"));
        }
示例#22
0
 public override string ToString()
 {
     return
         ($"FileActionType = {FileActionType.ToString()}, FileFullName={FileName}, NewFileName = {NewFileName}");
 }
示例#23
0
 public FileActionEventArgs(FileActionType action, UniFile file, object tag = null)
 {
     Action = action;
     File   = file;
     Tag    = tag;
 }