CreateFolder() public static method

创建文件夹
public static CreateFolder ( string pathName ) : DirectoryInfo,
pathName string
return DirectoryInfo,
Example #1
0
        private int genPageFile(string url, string file)
        {
            string webPath  = string.Format("{0}{1}", this.tbWebRootPath.Text.Trim(), url.Trim());
            string filePath = string.Format("{0}{1}", this.tbRootPath.Text.Trim(), file);
            string context  = "";

            try
            {
                context = NetClientUtil.doGet(webPath);
            }catch (Exception ex) {
                return(0);
            }
            FileInfo fileInfo = new FileInfo(filePath);

            string dirPath = fileInfo.Directory.ToString();

            FileUtil.CreateFolder(dirPath);
            if (FileUtil.WriteFile(filePath, context))
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Example #2
0
        protected virtual void Run(ClientPipelineArgs args)
        {
            ItemUri itemUri = ItemUri.Parse(args.Parameters["uri"]);
            Item    item    = Database.GetItem(itemUri);

            Error.AssertItemFound(item);
            bool   flag = true;
            string str1 = string.Concat(Settings.DataFolder.TrimStart(new char[] { '/' }), "\\", Settings.GetSetting("Sitecore.Scientist.MediaExportImport.ExportFolderName", "MediaExports"));

            if (!IsValidPath(str1))
            {
                str1 = HttpContext.Current.Server.MapPath("~/") + str1;
            }
            str1 = str1.Replace("/", "\\");
            FileUtil.CreateFolder(FileUtil.MapPath(str1));
            var innerfolders = item.Paths.FullPath.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var folder in innerfolders)
            {
                str1 = str1 + "\\" + folder;
                FileUtil.CreateFolder(FileUtil.MapPath(str1));
            }
            Log.Info(string.Concat("Starting export of media items to: ", string.Concat(Settings.DataFolder.TrimStart(new char[] { '/' }), "\\", Settings.GetSetting("Sitecore.Scientist.MediaExportImport.ExportFolderName", "MediaExports"))), this);
            ProgressBoxMethod progressBoxMethod = new ProgressBoxMethod(StartProcess);

            object[] objArray = new object[] { item, str1, flag };
            ProgressBox.Execute("Export Media Items...", "Export Media Items", progressBoxMethod, objArray);
        }
        public void ProcessMediaItems(Item rootMediaItem, bool recursive, string path = null)
        {
            if (rootMediaItem.TemplateID != TemplateIDs.MediaFolder && rootMediaItem.TemplateID != TemplateIDs.Node && rootMediaItem.TemplateID != TemplateIDs.MainSection)
            {
                string str = string.Concat("Processed ", Context.Job.Status.Processed, " items");
                Log.Info(str, this);
                JobStatus status = Context.Job.Status;
                status.Processed = status.Processed + (long)1;
                Context.Job.Status.Messages.Add(str);
                this.DownloadImage(new MediaItem(rootMediaItem), path);
                return;
            }
            else if (rootMediaItem.TemplateID == TemplateIDs.MediaFolder || rootMediaItem.TemplateID == TemplateIDs.Node)
            {
                var outputFolder = string.Empty;
                if (!string.IsNullOrEmpty(path))
                {
                    outputFolder = path + "\\" + rootMediaItem.Name;
                }
                else
                {
                    outputFolder = this.File + "\\" + rootMediaItem.Name;
                }
                FileUtil.CreateFolder(FileUtil.MapPath(outputFolder));

                Context.Job.Status.Messages.Add(string.Concat("Processing: ", rootMediaItem.Paths.ContentPath));
                foreach (Item child in rootMediaItem.GetChildren())
                {
                    this.ProcessMediaItems(child, true, outputFolder);
                }
                return;
            }
        }
Example #4
0
        private async void CreateFolderOnClick(object sender, RoutedEventArgs routedEventArgs)
        {
            string text = await DesignUtil.InputTextDialogAsync("Name");

            FileUtil.CreateFolder(App.sub + "\\" + currentPath + "\\" + text);
            InitListAsync(currentPath);
        }
Example #5
0
        public void LocalHotelTopImage(string hotelId, string basePath)
        {
            ICriteria icr = CreateCriteria <HotelImageModel>();

            icr.Add(Restrictions.Eq("hotelFk", hotelId));
            IList <HotelImageModel> images = icr.List <HotelImageModel>();
            WebClient client = new WebClient();

            foreach (HotelImageModel image in images)
            {
                if (image.title.Contains("外观"))
                {
                    string folder = string.Format("{0}/{1}", basePath.TrimEnd('/'), hotelId);
                    FileUtil.CreateFolder(folder);
                    string filePattern = "";
                    if (image.isThum())
                    {
                        filePattern = "{0}/thum{1}";
                    }
                    else if (image.isNormal())
                    {
                        filePattern = "{0}/normal{1}";
                    }
                    else
                    {
                        continue;
                    }
                    string filePath = string.Format(filePattern, folder, FileUtil.GetPostfixStr(image.imgUrl));

                    client.DownloadFile(image.imgUrl, filePath);
                }
            }
        }
Example #6
0
    public void Initialize(Action onComplete)
    {
        if (onComplete != null)
        {
            onStartupFunc = onComplete;
        }

        //取消 Destroy 对象

        InitConsole();
        InitUIRoot();
        InitResolution();

        //平台初始化
        AppPlatform.Initialize();

        //基本设置
        Screen.sleepTimeout                    = SleepTimeout.NeverSleep;
        Application.targetFrameRate            = Global.FrameRate;
        UnityEngine.QualitySettings.vSyncCount = Global.VSyncCount;

        //挂载管理器并初始化
        ManagerCollect.Instance.AddManager <TaskManager>(ManagerName.Task);
        ManagerCollect.Instance.AddManager <AssetLoadManager>(ManagerName.AssetLoad);
        ManagerCollect.Instance.AddManager <SoundManager>(ManagerName.Sound);
        ManagerCollect.Instance.AddManager <GestureManager>(ManagerName.Gesture);

        //创建运行时资源目录
        FileUtil.CreateFolder(AppPlatform.RuntimeAssetsPath);

        AssetsUpdater.Run(() =>
        {
            LoadAssetbundleManifest();
        });
    }
Example #7
0
        /// <summary>
        /// 打印捕捉到的错误日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void UnHandlerExceptionEventHandler(object sender, UnhandledExceptionEventArgs args)
        {
            try
            {
                string path = mFilePath;
                //根目录不存在就创建一个目录文件夹
                FileUtil.CreateFolder(path);

                //将根目录路径和文件名组合
                path += "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                //如果文件不存在,就创建一个文件,否则就加载文件,并讲对象赋值给该对象
                if (mStreamWriter == null)
                {
                    mStreamWriter = !System.IO.File.Exists(path) ? System.IO.File.CreateText(path) : System.IO.File.AppendText(path);
                }
                //开始写入文件
                mStreamWriter.WriteLine("/************************" + DateTime.Now.ToString("HH:mm:ss.ff") + "************************/");
                //写入发送者
                mStreamWriter.WriteLine("Sender:" + sender);
                //写入时间信息
                mStreamWriter.WriteLine("Args:" + args.ExceptionObject);
            }
            finally
            {
                if (mStreamWriter != null)
                {
                    mStreamWriter.Flush();
                    mStreamWriter.Close();
                    mStreamWriter = null;
                }
            }
            RunReset();
        }
Example #8
0
        public JsResultObject LocalHotelImage(string basePath, HotelImageModel image, bool isTop)
        {
            JsResultObject re     = new JsResultObject();
            WebClient      client = new WebClient();
            string         folder = string.Format("{0}/{1}", basePath.TrimEnd('/'), image.hotelFk);

            FileUtil.CreateFolder(folder);
            string filePattern = "";
            string filePath    = "";

            if (isTop)
            {
                if (image.isThum())
                {
                    filePattern = "{0}/top.thum{1}";
                }
                else if (image.isNormal())
                {
                    filePattern = "{0}/top.normal{1}";
                }
                filePath = string.Format(filePattern, folder, FileUtil.GetPostfixStr(image.imgUrl));
            }
            else
            {
                if (image.isThum())
                {
                    filePattern = "{0}/{1}.thum{2}";
                }
                else if (image.isNormal())
                {
                    filePattern = "{0}/{1}.normal{2}";
                }
                else if (image.isAround())
                {
                    filePattern = "{0}/{1}.around{2}";
                }
                else
                {
                    re.code = JsResultObject.CODE_ERROR;
                    return(re);
                }
                filePath = string.Format(filePattern, folder, image.title, FileUtil.GetPostfixStr(image.imgUrl));
            }
            try
            {
                client.DownloadFile(image.imgUrl, filePath);
                re.rowNum = 1;
                re.msg    = "保存图片:" + filePath;
            }
            catch (Exception ex)
            {
                re.rowNum = 0;
                re.msg    = ex.Message;
            }
            return(re);
        }
Example #9
0
        protected virtual void Run(ClientPipelineArgs args)
        {
            var  uri  = ItemUri.Parse(args.Parameters["uri"]);
            Item item = Database.GetItem(uri);

            Error.AssertItemFound(item);

            if (!args.IsPostBack)
            {
                UrlString urlString = ResourceUri.Parse("control:ExportMedia").ToUrlString();
                uri.AddToUrlString(urlString);
                SheerResponse.ShowModalDialog(urlString.ToString(), "280", "220", "", true);
                args.WaitForPostBack();
                return;
            }

            if (string.IsNullOrEmpty(args.Result) || args.Result == "undefined")
            {
                return;
            }

            string[] paramsArray    = args.Result.Split('|');
            string   exportFileName = paramsArray[0];

            if (string.IsNullOrWhiteSpace(exportFileName))
            {
                return;
            }

            bool recursive = extractRecursiveParam(paramsArray);

            string exportfolderName = Settings.DataFolder + "/" +
                                      Settings.GetSetting("SharedSource.MediaExporterModule.ExportFolderName", "MediaExports");

            string exportFileNameWithExtension = exportFileName.EndsWith(".zip") ? exportFileName : exportFileName + ".zip";

            FileUtil.CreateFolder(FileUtil.MapPath(exportfolderName));

            string zipPath = FileUtil.MapPath(FileUtil.MakePath(exportfolderName,
                                                                exportFileNameWithExtension,
                                                                '/'));

            Log.Info("Starting export of media items to: " + zipPath, this);
            Sitecore.Shell.Applications.Dialogs.ProgressBoxes.ProgressBox.Execute(
                "Export Media Items...",
                "Export Media Items",
                new Sitecore.Shell.Applications.Dialogs.ProgressBoxes.ProgressBoxMethod(StartProcess),
                new[] { item as object, zipPath, recursive });

            Context.ClientPage.ClientResponse.Download(zipPath);
        }
    public void Initialize(Action onComplete)
    {
        if (onComplete != null)
        {
            onStartupFunc = onComplete;
        }
        else
        {
            DebugConsole.Log("未设置游戏启动函数");
        }

        //取消 Destroy 对象
        DontDestroyOnLoad(gameObject);

        InitConsole();
        InitUIRoot();
        InitResolution();

        //平台初始化
        AppPlatform.Initialize();

        //基本设置
        Screen.sleepTimeout                    = SleepTimeout.NeverSleep;
        Application.targetFrameRate            = Global.FrameRate;
        UnityEngine.QualitySettings.vSyncCount = Global.VSyncCount;

        //挂载管理器并初始化
        ManagerCollect.Instance.AddManager(ManagerName.Script, ScriptManager.Instance);
        ManagerCollect.Instance.AddManager(ManagerName.Panel, PanelManager.Instance);
        ManagerCollect.Instance.AddManager(ManagerName.Popups, PopupsManager.Instance);

        ManagerCollect.Instance.AddManager <ResourcesUpdateManager>(ManagerName.ResourcesUpdate);
        ManagerCollect.Instance.AddManager <CoroutineManager>(ManagerName.Coroutine);
        ManagerCollect.Instance.AddManager <TimerManager>(ManagerName.Timer);
        ManagerCollect.Instance.AddManager <AssetLoadManager>(ManagerName.Asset);
        ManagerCollect.Instance.AddManager <SceneLoadManager>(ManagerName.Scene);
        ManagerCollect.Instance.AddManager <MusicManager>(ManagerName.Music);
        ManagerCollect.Instance.AddManager <GestureManager>(ManagerName.Gesture);

        //创建运行时资源目录
        FileUtil.CreateFolder(AppPlatform.RuntimeAssetsPath);

        Global.ResourcesUpdateManager.ResourceUpdateStart(() =>
        {
            LoadAssetbundleManifest();
        });
    }
Example #11
0
        private async void ShareOnClick(object sender, RoutedEventArgs routedEventArgs)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                ContentDialog noWifiDialog = new ContentDialog
                {
                    Title           = "Error",
                    Content         = "Please select file.",
                    CloseButtonText = "Ok"
                };
                ContentDialogResult result = await noWifiDialog.ShowAsync();
            }
            else
            {
                string text = await DesignUtil.InputTextDialogAsync("Email:");

                string text2 = "  ";

                if (String.IsNullOrEmpty(text) == true || String.IsNullOrEmpty(text2) == true)
                {
                    await new MessageDialog("Email or folder text is empty!", "Error").ShowAsync();
                }
                else
                {
                    try
                    {
                        File f        = (File)listView1.SelectedItems[0];
                        var  basePath = f.FilePath.Split(App.sub).First();
                        text2 = await DesignUtil.InputTextDialogAsync("Folder Name:",
                                                                      basePath + App.sub + "\\Shared\\");

                        string       destPath = App.sub + "\\Shared\\" + text2;
                        SettingsPage sp       = new SettingsPage();
                        await sp.sendEmailAsync(
                            App.given_name + " is sharing with you: " + basePath + App.sub + "\\Shared\\" + text2,
                            text);

                        FileUtil.CreateFolder(destPath);
                        FileUtil.ShareFiles(f.FilePath, destPath);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
        }
Example #12
0
        public void LocalHotelImage(string hotelId, string basePath)
        {
            ICriteria icr = CreateCriteria <HotelImageModel>();

            icr.Add(Restrictions.Eq("hotelFk", hotelId));
            IList <HotelImageModel> images = icr.List <HotelImageModel>();
            WebClient client = new WebClient();

            foreach (HotelImageModel image in images)
            {
                string folder = string.Format("{0}/{1}/{2}", basePath.TrimEnd('/'), hotelId, image.imgType);
                FileUtil.CreateFolder(folder);
                string filePath = string.Format("{0}/{1}{2}", folder, image.title, FileUtil.GetPostfixStr(image.imgUrl));

                client.DownloadFile(image.imgUrl, filePath);
            }
        }
Example #13
0
        public void CreateSite()
        {
            var sitePath = Constant.Server.MapPath($"~/{SiteName}");

            FileUtil.CreateFolder(sitePath, false);
            FileUtil.CreateFolder($"{sitePath}/js", false);
            FileUtil.CreateFolder($"{sitePath}/css", false);
            FileUtil.CreateFolder($"{sitePath}/control", false);
            FileUtil.CreateFolder($"{sitePath}/resource", false);

            CreateIcon();
            if (Option == "save")
            {
                SaveTemp();
            }
            if (Option == "ReName")
            {
                ReNameTemp();
            }
        }
Example #14
0
        public void LocalHotelImage(string basePath)
        {
            ICriteria icr = CreateCriteria <HotelImageModel>();
            IList <HotelImageModel> images = icr.List <HotelImageModel>();
            WebClient client = new WebClient();

            foreach (HotelImageModel image in images)
            {
                string folder = string.Format("{0}/{1}", basePath.TrimEnd('/'), image.hotelFk);
                FileUtil.CreateFolder(folder);
                string filePattern = "";
                if (image.isThum())
                {
                    filePattern = "{0}/{1}.thum{2}";
                }
                else if (image.isNormal())
                {
                    filePattern = "{0}/{1}.normal{2}";
                }
                else if (image.isAround())
                {
                    filePattern = "{0}/{1}.around{2}";
                }
                else
                {
                    continue;
                }
                string filePath = string.Format(filePattern, folder, image.title, FileUtil.GetPostfixStr(image.imgUrl));
                try
                {
                    client.DownloadFile(image.imgUrl, filePath);
                    System.Console.WriteLine("保存图片:" + filePath);
                }
                catch (Exception ex) {
                    System.Console.WriteLine(ex.Message);
                }
            }
        }
        protected override string BuildPackage()
        {
            var packageName = Path.GetFileNameWithoutExtension(FileName);
            var folder      = Path.Combine(TempFolder.Folder, "nuget." + packageName);

            var index = 0;

            while (FileUtil.Exists(folder))
            {
                folder = Path.Combine(TempFolder.Folder, "nuget." + packageName + "[" + index + "]");
                index++;
            }

            folder = FileUtil.MapPath(folder);
            FileUtil.CreateFolder(folder);

            var nuspecFileName = Path.Combine(folder, packageName + ".nuspec.txt");

            var serializationFolder = Path.Combine(folder, "serialization");
            var packageId           = Regex.Replace(PackageName, "\\W", string.Empty);

            using (var output = new XmlTextWriter(nuspecFileName, Encoding.UTF8))
            {
                output.Formatting = Formatting.Indented;

                output.WriteStartElement("package");

                output.WriteStartElement("metadata");
                output.WriteElementString("id", packageId);
                output.WriteElementString("version", Version);
                output.WriteElementString("title", PackageName);
                output.WriteElementString("authors", Author);
                output.WriteElementString("owners", Publisher);
                output.WriteElementString("description", Readme);
                output.WriteElementString("summary", Readme);
                output.WriteElementString("releaseNotes", Comment);
                output.WriteElementString("copyright", string.Empty);
                output.WriteElementString("tags", "Sitecore Package");

                WriteMetaData(output);

                output.WriteEndElement();

                output.WriteStartElement("files");

                foreach (var fileName in Files)
                {
                    if (FileUtil.IsFolder(fileName))
                    {
                        foreach (var file in Directory.GetFiles(FileUtil.MapPath(fileName), "*", SearchOption.AllDirectories))
                        {
                            var fileInfo = new FileInfo(file);
                            if ((fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                            {
                                continue;
                            }

                            if ((fileInfo.Attributes & FileAttributes.System) == FileAttributes.System)
                            {
                                continue;
                            }

                            output.WriteStartElement("file");

                            output.WriteAttributeString("src", file);
                            output.WriteAttributeString("target", TargetFileFolder + FileUtil.UnmapPath(file, false));

                            output.WriteEndElement();
                        }
                    }
                    else
                    {
                        output.WriteStartElement("file");

                        output.WriteAttributeString("src", FileUtil.MapPath(fileName));
                        output.WriteAttributeString("target", TargetFileFolder + FileUtil.UnmapPath(fileName, false));

                        output.WriteEndElement();
                    }
                }

                // make sure install.ps1 and init.ps1 are run
                if (!Files.Any() || TargetFileFolder != "content")
                {
                    if (Items.Any())
                    {
                        var fileName = Path.Combine(serializationFolder, "nuget\\about.txt");
                        FileUtil.CreateFolder(Path.GetDirectoryName(fileName) ?? string.Empty);
                        File.WriteAllText(fileName, "This file ensures that the install.ps1 and init.ps1 PowerShell scripts are run when installing the NuGet package.");

                        output.WriteStartElement("file");

                        output.WriteAttributeString("src", fileName);
                        output.WriteAttributeString("target", "content\\nuget\\about.txt");

                        output.WriteEndElement();
                    }
                }

                foreach (var item in Items)
                {
                    var baseFileName = item.Database.Name + FileUtil.NormalizeWebPath(item.Paths.Path).Replace('/', '\\') + ".item";

                    var fileName = Path.Combine(serializationFolder, baseFileName);
                    FileUtil.CreateFolder(Path.GetDirectoryName(fileName) ?? string.Empty);

                    Manager.DumpItem(fileName, item);

                    output.WriteStartElement("file");

                    output.WriteAttributeString("src", fileName);
                    output.WriteAttributeString("target", "serialization\\" + baseFileName);

                    output.WriteEndElement();
                }

                WriteFiles(output);

                output.WriteEndElement();

                output.WriteEndElement();
            }

            return(nuspecFileName);
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            //clear session
            Session.Clear();

            btnDownload.Visible = false;

            //get selected folder
            var itemId = new ID(ddMediaFolders.SelectedValue);

            var db = Database.GetDatabase(ddDataBase.SelectedValue.ToLower());

            var selectedFolder = db.Items.GetItem(itemId);


            //set folder to export file
            var exportfolderName = Settings.DataFolder + "/MediaEssentials/ExportMedia/" + selectedFolder.Name;

            _exportFileNameWithExtension = selectedFolder.Name + ".zip";

            FileUtil.CreateFolder(FileUtil.MapPath(exportfolderName));


            //map file path
            _filePath = FileUtil.MapPath(FileUtil.MakePath(exportfolderName, _exportFileNameWithExtension, '/'));

            var mediaLibraryItem = db.GetItem(MediaLibraryUtils.MediaLibraryId);

            var allMediaItems = _mediaLibrary.GetMediaItems(db, selectedFolder, mediaLibraryItem,
                                                            chkIncludeSubFolders.Checked, chkIncludeSystemFolder.Checked);


            //get total of images exported excluding the pre-defined templates below
            var excludedTemplates = new List <string>
            {
                TemplateIDs.MediaFolder.ToString(),
                TemplateIDs.MainSection.ToString(),
                TemplateIDs.Node.ToString()
            };

            var items = allMediaItems.ToArray();

            var totalImagesExported = items
                                      .Select(i => excludedTemplates.FirstOrDefault(x => x.Contains(i.Template.ID.ToString())))
                                      .Count(match => match == null);


            var output = new StringBuilder();

            if (totalImagesExported == 0)
            {
                output.Clear();
                output.AppendLine("There is no media to export within the options set.");

                //output of last execution
                lbOutput.Text = output.ToString().Replace(Environment.NewLine, "<br />");

                return;
            }



            //fill in output
            output.Clear();

            output.AppendLine("Total of Images Exported: " + totalImagesExported);

            output.AppendLine("File Location on Server: " + exportfolderName);

            output.AppendLine();
            output.AppendLine("---- Media Items Exported ----");
            output.AppendLine();

            var templates = items.GroupBy(x => x.TemplateID);


            foreach (IGrouping <Sitecore.Data.ID, Item> item in templates)
            {
                if (item.Key == TemplateIDs.MediaFolder ||
                    item.Key == TemplateIDs.MainSection ||
                    item.Key == TemplateIDs.Node)
                {
                    continue;
                }

                foreach (var i in item)
                {
                    output.AppendLine("Item ID: " + i.ID);
                    output.AppendLine("Item Name: " + i.Name);
                    output.AppendLine("Item Path: " + i.Paths.Path);
                    output.AppendLine();
                }
            }


            ZipWriter = new ZipWriter(_filePath);

            foreach (var i in items)
            {
                if (!chkIncludeSystemFolder.Checked && i.Paths.Path.ToLower()
                    .Contains(mediaLibraryItem.Paths.Path.ToLower() + "/system"))
                {
                    continue;
                }

                ProcessMediaItems(i);
            }

            ZipWriter.Dispose();


            Session["filePath"] = _filePath;
            Session["exportFileNameWithExtension"] = _exportFileNameWithExtension;

            btnDownload.Visible = true;

            //output of last execution
            lbOutput.Text = output.ToString().Replace(Environment.NewLine, "<br />");
        }
 /// <summary>
 /// Creates a SQLite connection
 /// </summary>
 /// <param name="folderName">The folder name of the desiered database location</param>
 /// <param name="databaseName">The sqlite database name</param>
 public void CreateConnection(string folderName, string databaseName)
 {
     FileUtil.CreateFolder(folderName);
     sqliteConnection = new SQLiteConnection($@"Data Source={folderName}\{databaseName};Version=3;");
     FolderPath = $@"{folderName}\{databaseName}";
 }
Example #18
0
        /// <summary>
        /// 从旧乐谱库直接复制到新乐谱库
        /// </summary>
        /// <param name="dbPath"></param>
        /// <param name="oldHomePath"></param>
        /// <param name="autoCopy"></param>
        private static void CheckOldHome(string dbPath, string oldHomePath, bool autoCopy)
        {
            Console.WriteLine("检查旧乐谱谱库");
            if (string.IsNullOrEmpty(oldHomePath))
            {
                Console.WriteLine("没有指定旧乐谱路径");
                return;
            }
            InitDB(dbPath);
            var ypHomePath = ConfigUtil.Instance.Load().PianoScorePath;
            var dataSet    = SQLite.SqlTable("SELECT * FROM tan8_music_old", null);
            var total      = dataSet.Rows.Count;
            var copyTotal  = 0;
            var cur        = 0;

            foreach (DataRow dataRow in dataSet.Rows)
            {
                Console.WriteLine(dataRow["name"] + "   ----进度:" + ++cur + "/" + total + "");
                if (Directory.Exists(Path.Combine(oldHomePath, dataRow["name"] as string)))
                {
                    var files       = Directory.GetFiles(Path.Combine(oldHomePath, dataRow["name"] as string));
                    var hasPlayFile = false;
                    if (files.Length > 0)
                    {
                        foreach (var fileName in files)
                        {
                            if (fileName.EndsWith("ypdx") || fileName.EndsWith("ypa2"))
                            {
                                hasPlayFile = true;
                                break;
                            }
                        }
                    }
                    if (hasPlayFile)
                    {
                        if (!autoCopy)
                        {
                            continue;
                        }

                        var i = SQLite.ExecuteNonQuery("insert or ignore into tan8_music(ypid, `name`, star, yp_count, origin_data) VALUES (@ypid, @name, @star, @yp_count, @origin_data)",
                                                       new List <SQLiteParameter>
                        {
                            new SQLiteParameter("@ypid", dataRow["ypid"]),
                            new SQLiteParameter("@name", dataRow["name"]),
                            new SQLiteParameter("@star", 0 as object),
                            new SQLiteParameter("@yp_count", dataRow["yp_count"]),
                            new SQLiteParameter("@origin_data", dataRow["origin_data"])
                        });

                        if (i > 0)
                        {
                            //复制文件
                            if (!Directory.Exists(Path.Combine(ypHomePath, Convert.ToString(dataRow["ypid"]))))
                            {
                                FileUtil.CreateFolder(Path.Combine(ypHomePath, Convert.ToString(dataRow["ypid"])));
                            }
                            foreach (var file in files)
                            {
                                FileUtil.CopyFile(file, Path.Combine(ypHomePath, Convert.ToString(dataRow["ypid"]), Path.GetFileName(file)));
                            }
                            copyTotal++;
                        }
                    }
                }
            }
            Console.WriteLine("共复制" + copyTotal + "个目录");
        }
        /// <summary>
        /// 执行同步文件的后台任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoSyncFileTask(object sender, DoWorkEventArgs e)
        {
            var winProgress = new MainWindowStatusNotify()
            {
                alertLevel       = AlertLevel.RUN,
                animateProgress  = true,
                progressDuration = 100,
                nowProgress      = 0
            };
            var isTaskStop = false;
            //当前执行的队列编号
            var curTaskNo = 1;
            //当前队列最大元素数量
            var maxedQueueCount = mSyncTaskQueue.Count;

            while (mSyncTaskQueue.Count > 0)
            {
                var arg    = new DeviceSyncTaskArgs();
                var isPick = mSyncTaskQueue.TryDequeue(out arg);
                if (!isPick)
                {
                    continue;
                }
                //每个队列的分片进度
                double eachBaseProgress = 0;
                //筛选WPD设备
                using (var device = arg.Device)
                {
                    device.Connect();

                    //检查目标文件夹是否存在, 不存在则创建
                    if (!Directory.Exists(arg.Item.PcFolderNameView))
                    {
                        FileUtil.CreateFolder(arg.Item.PcFolderNameView);
                    }
                    var targetMobileFolder = Path.Combine(arg.DevicePath, arg.Item.MobileFolderNameView);
                    if (!device.DirectoryExists(targetMobileFolder))
                    {
                        device.CreateDirectory(targetMobileFolder);
                    }

                    //将两端的文件合并到一个集合
                    var allItems = arg.Item.PcItemList.ToList();
                    allItems.AddRange(arg.Item.MobileItemList.ToList());
                    var fileCounter = 1;
                    allItems.ForEach((syncFile) => {
                        //检查任务是否取消
                        if (mSyncFileBgWorker.CancellationPending)
                        {
                            isTaskStop = true;
                            return;
                        }
                        //如果队列数量增大超过初始量, 记录一个最大数量
                        if (mSyncTaskQueue.Count + 1 > maxedQueueCount)
                        {
                            maxedQueueCount = mSyncTaskQueue.Count + 1;
                        }
                        //当前队列数量=此队列拥有过的最大数量
                        var curQueueCount = maxedQueueCount;
                        //计算每个队列的分片进度
                        eachBaseProgress = 100 / curQueueCount;
                        //每个队列的基础进度, 从0开始, 以分片进度递增
                        double baseProgress = 100 - (mSyncTaskQueue.Count + 1) * eachBaseProgress;
                        //计算每个文件的分片进度
                        double eachFileProgress = eachBaseProgress / allItems.Count;
                        //文件的执行进度, 从0开始递增
                        double fileProgress = eachFileProgress * fileCounter - eachFileProgress;
                        //总进度 = 基础进度 + 文件进度
                        WindowUtil.CalcProgress(winProgress,
                                                string.Format("主任务 [{0}/{1}], 子任务 [{2}/{3}], 正在复制 [ {4} ]", curTaskNo, curQueueCount, fileCounter, allItems.Count, syncFile.NameView),
                                                baseProgress + fileProgress);
                        arg.Progress     = winProgress;
                        arg.ProgressType = SyncTaskProgressType.SUB_ITEM_FINISH;
                        mSyncFileBgWorker.ReportProgress(0, arg);
                        //执行同步
                        if (syncFile.SourceView == SyncDeviceType.PC)
                        {
                            //电脑端, 需要复制到移动端
                            var targetFolder = Path.Combine(arg.DevicePath, arg.Item.MobileFolderNameView);
                            using (FileStream stream = System.IO.File.OpenRead(Path.Combine(arg.Item.PcFolderNameView, syncFile.NameView)))
                            {
                                device.UploadFile(stream, Path.Combine(targetFolder, syncFile.NameView));
                            }
                        }
                        else
                        {
                            MediaFileInfo fileInfo = device.GetFileInfo(Path.Combine(arg.DevicePath, arg.Item.MobileFolderNameView, syncFile.NameView));
                            fileInfo.CopyTo(Path.Combine(arg.Item.PcFolderNameView, syncFile.NameView));
                        }
                        fileProgress = eachFileProgress * fileCounter;
                        WindowUtil.CalcProgress(winProgress,
                                                string.Format("主任务 [{0}/{1}], 子任务 [{2}/{3}], 正在复制 [ {4} ]", curTaskNo, curQueueCount, fileCounter, allItems.Count, syncFile.NameView),
                                                baseProgress + fileProgress);
                        arg.Source         = syncFile.SourceView;
                        arg.DeviceSyncItem = syncFile;
                        mSyncFileBgWorker.ReportProgress(0, arg);
                        fileCounter++;
                    });
                    device.Disconnect();
                }
                arg.IsOk         = !isTaskStop;
                arg.ProgressType = SyncTaskProgressType.QUEUE_FINISH;
                if (!isTaskStop)
                {
                    //一个队列执行完之后, 发送当前队列进度
                    WindowUtil.CalcProgress(arg.Progress, string.Format("主任务 [{0}/{1}]同步完成", curTaskNo, maxedQueueCount), curTaskNo * eachBaseProgress);
                    mSyncFileBgWorker.ReportProgress(0, arg);
                    curTaskNo++;
                }
                else
                {
                    mSyncFileBgWorker.ReportProgress(0, arg);
                }
            }
            e.Result = !isTaskStop;
        }